T-SQL (SS2K8) :: Find Best Index For Specific Query
Dec 28, 2014
This is my table:
use tempdb
go
if object_id('Data', 'u') is not null drop table Data
go
with temp as (
select top 10000 row_number() over (order by c1.object_id) Id
from sys.columns c1 cross join sys.columns c2
[code]....
What index would be best for these three queries? With best I mean the execution time, I don't care about additional space.
This is the index I currently use:
create nonclustered index Ix_Data on Data (StateId, PalletId, BoxId, Id)
The execution plan is SELECT (0%) - Stream Aggregate (10%) - Index Scan (90%).
Can this be optimized (maybe to use Index Seek method)?
insert into #temp (Cabstamp,account,Document, origin, debit, credit, datalc) select 'ADM12345',111,'CMP-01','FO',1000,0, '20150110' union select 'ADM12345',112,'CMP-01','FO', 500, 0,'20150110' union select 'ADM12345',6811,'CMP-01','DO',0,1500,'20150110' union
SELECT CASE WHEN CHARINDEX(' ', Supervisor, CHARINDEX(' ', Supervisor, 0) + 1) > 0 THEN REPLACE(Supervisor, SUBSTRING(Supervisor, CHARINDEX(' ', Supervisor, CHARINDEX(' ', Supervisor, 0) + 1), LEN(Supervisor)), '') ELSE Supervisor END AS NewSupervisor from data d
However, I stumble when Middle Name exists somewhere in the name as Replace function repalces every occurrence of the string. For ex: "Allen, Gary G" becomes "Allen,ary"
Do we have any way to say sql to replace after certain index?
We're looking at optimizing some of our tables because we have indexes on columns that are not used. So for example we might have a table that has 6GB of data and 4GB in indexes (according to sp_spaceused). We need to know how much of the 4GB of indexes is consumed by each of the indexes individually. I've tried dbcc showcontig, but that doesn't tell me the amount of space used by the index that I run it for.
Second (and by far not as important), is there a way to determine how much space is being consumed by data in a specific column. The original creator of some of the tables added an incrementing identity column that is used no where in the system. I'd like to be able to say..."If we drop this column we'll save XXX in space."
Knowing the index space is more critical, the column space would be nice but not necessary.
Ok, please pardon my complete ignorance; but I am extremely SQL challenged. I manage the server right now and I am the closest thing to a DBA at the moment with this server.
Here is the problem. I have a job that runs every hour and until last week it was running without any problems. Now, once a day it hangs, and I end up having to restart sql to get it to be functional again. I guess I could just kill the spid, but regardless, it's fails.
It doesn't happen at the same time each day. I thought it was from the backups doing a SQL backup job, but I eliminated that possibility. I can't find what is causing the problem, because the SQL logs just stop at the time that this happens. It's like some other job/query is running and taking all the sql server resources. But I can never catch it when it's happening and I have no event logs or SQL logs to go on.
Is there any query that I can run to find what happened around the specific time the job failed to run? I just need to find what process did what when this job stopped working.
Again, I apologize if my lack of SQL knowledge is making me ask dumb questions, but I am really lost.
I need to know /observe for a period like 10 days in a row HOW MANY TIMES a specific Stored Proc is executed on the server. How can I do that? is there a way to precisely know a number of such calls via DMVs?
The 2 digit number that appears on line 1, 7 and 13 (only in this example) i need to have added to the begin of each value below it until the next 2 digit number is encountered. The desired result set would look like:
I'm working on a join between two tables where I only want one row returned... I'm matching on two columns between two tables. One of those columns in the target table could be null. I only want one record returned.
I've a table that stores operationcode for each jobnumber. The jobnumber can have multiple operationcode. From the below DDL, I need to show all the jobs that have operation codes as 2001 and 2002. In the below DDL Jobnumber 80011 has both the operation codes 2001 and 2002 so this job will display on the report.
On the other hand Job 80021 only has operationcode 2001 and I do not want this job to show up on the report.
I need to show all the operationcodes for a job if it has operationcode 2001 and 2002.
USE tempdb; GO DECLARE @TEST_DATA TABLE ( DT_ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED , OperationCodeVARCHAR(10) NOT NULL , EmployeeCode VARCHAR(10) NOT NULL
i am trying to make a highscore table and i would like when the user enters a score for them to be able to see what position they are in the database without having to take out all the data. i have looked at a few methods and was wondering which one is the best solution and how i would go about implementing it
I want to write SQL that will search the tables in a database for a specific column, like this. For instance, I have a column "Unique_ID" that is in many of our tables (hundreds) but not in others and want to find out the tables it is in. It is always the first column.
I tried to find a system stored procdure to do this but couldn't and tried to create a script using the sysobjects and syscolumns tables in the Master db, but came to a roadblock because they don't seem to be related at all.
I would surely appreciate if someone else has already done this!
The sql listed above does execute the stored procedure called [dbo].[sproom] successfully and returns all the data all the rows from the stored procedure multiple times. However can you tell me the following:
1. How can I have the stored procedure return distinct rows? 2. I want the stored procedure to return selected columns. I tried using the OUTPUT parameter for some of the columns, but I got the error message, "Procedure or function spHomeroom has too many arguments specified.".
A solution might be to change the stored procedure, but I would prefer not to since this is a generic stored procedure that I believe a lot of t-sqls and stored procedures will use.
I have a stored procedure that runs every 5 minutes. I have one block in the procedure that will only run if there are records in a temp table. In addition, I would like this block to run only if the current time is between 0 and 5 minutes past the hour or between 30 and 35 minutes past the hour.
Currently, my block looks like this: IF OBJECT_ID('tempdb..#tmpClosedPOs') IS NOT NULL BEGIN
I can get the current minutes of the current time by using:
Select DATEPART(MINUTE,GetDate())
I know that it should be simple, but I'm pretty new at Stored Procedures. How do I alter the IF statement to check for the time and only run the block if it's between the times I stated? I started to DECLARE @Minutes INT, but wasn't sure where to go from there.
Can you create an UPDATE TRIGGER and use some typeof code to figure out which SP just updated the current table?If not how can i achieve what i want?I tried to run SQL Profiler and i don't understand why i can'tsimply have the Profiler filter events only for the specific database idand the table's object id i chose?What am i doing wrong with SQL Profiler? I was testing thisthrough SQL EM. I had the filters chosen for a specific database idand a specific table's object id, yet when i open another table SQLProfiler captures that information too.Thank you
write a query which retrieves only unique rows excluding some columns.
IdStatusmanager Team Comments Proj number Date 19391New XUnassigned One 3732.0 16-Apr-14 19392Can YCustomer Two 3732.0 17-Apr-14 19393Can YCustomer Two 3732.0 17-Apr-14 19394Can YCustomer One 3732.0 18-Apr-14 19395New YCustomer One 3732.0 19-Apr-14 19396New YCustomer One 3732.0 21-Apr-14 19397New ZCustomer One 3732.0 20-Apr-14
In the above table project number and id shouldn't be considered and I should get the unique rows considering rest of columns and sorted based on date. Expected result is
IdStatusmanager Team Comments Proj number Date 19391New XUnassigned One 3732.0 16-Apr-14 19392Can YCustomer Two 3732.0 17-Apr-14 19394Can YCustomer One 3732.0 18-Apr-14 19395New YCustomer One 3732.0 19-Apr-14 19397New ZCustomer One 3732.0 20-Apr-14 19396New YCustomer One 3732.0 21-Apr-14
Hi all, We have a table that is full text enabled and it is working fine, but the full text search doesn't returns any record for the following case
select * from let_catalog_search where contains(search_field,'"Bulk Process 1*"') even though there exist records that satisfy the condition in the table, the record that i am talking abt is "bulk process 1 with price bp100-ilt1-00200136 bp100-ilt1"
If I remove the last 1 from the search string i get lot of records, Can anybody help me out.
I'm trying to find a specific string (a name) and replace it with another inside of a VARCHAR(7000) field. Unfortunately, there are names like Ted and Ken that I'm trying to replace. I would like to leave words like Broken, admitted, etc... intact.
UPDATEtbl SETBody = LEFT(REPLACE(tbl.Body, pm.OldFirstName, p.FirstName), 7000) FROM Table tbl JOIN Person p ON p.PersonID = tbl.PersonID JOIN PersonMap pm ON pm.PersonID = p.PersonID AND LEN(pm.OldFirstName) > 2 WHEREtbl.Body LIKE '%[^a-z]'+pm.OldFirstName+'[., ]%
'The problem I'm running into is that the '[, ]%' in the LIKE excludes any record that ends with the FirstName because it is requiring either a space, comma or period after the name. Is there some way to add an empty string to the list of acceptable characters as that would cover any scenario in the data? I would prefer not to add all characters except space, comma and period, but I guess I could do that.
I have a Transactional table containing IDs that relate to each other. The table highlights the transactions that move one ID to another, by storing an ID and a IDNew (Basically from ID to ID).
My requirement is to create a Inline Table Valued Function that will efficiently return a single ID column to show all related IDs by looking at the ID and the IDNew fields. I need to pass in a single ID to get all relations or a list of IDs through xml.
I have managed to achieve this by making use of two recursive cte's and then combining the results with union statements to create a distinct list of values.
IF OBJECT_ID (N'tempdb..#Trans', N'U') IS NOT NULL BEGIN DROP TABLE #Trans END CREATE TABLE #Trans ( TranID int identity(1,1),
I would like to create an index with a few options but having issues trying to parse and run it successfully. The issue is near the end of the statement. Here's the create statement below:
-- Index PSAPSACTIVITYDEFN on table PSACTIVITYDEFN IF EXISTS(SELECT 1 FROM sysindexes si INNER JOIN sysobjects so ON so.id = si.id
I have written an update, if i see the execution plan of that update, it is showing the Non Clustered index are updated. I am not able to understand the fact, that when there was no change in Leaf level root data how does Non clustered index got updated.
I am trying to create a temp table with a non-clustered index.
Originally I tried to create the index after I created the table.
This seemed to work fine, so I added my stored procedure to our Production environment.
However, when two users called the stored procedure at once I got the following error:
There is already an object named 'IX_tmpTableName' in the database. Could not create constraint. See previous errors.
I then found that SQL Server does generate unique names for the temp table but not all the objects associated with the temp table if they are explicitly named.
This is easy enough to solve for a PRIMAY KEY or UNIQUE constraint because the do not have to be named.
Is there a way to create an non-clustered index on a temp table without naming it?
In a Stored Proc I am creating the following temp table and index:
CREATE TABLE [dbo].[#ShipTo]( [Ship_to_Num] [int] NOT NULL, [Country_key] [nvarchar](3) NULL, CONSTRAINT [PK_ShipTo] PRIMARY KEY CLUSTERED ( [ship_to_Num] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY]
The stored Proc runs fine from "exec", but when you batch into a Job it gives the error that "PK_ShipTo" already exists! I even put in a drop table on #ShipTo, but the same effect.
I'm running SQL Server 2008 R2 with latest patch. I'm performing all index maintenance online. How long the final phase of the index operation takes? Does the size of the index matter and if any blocking occurs, does the duration increase because the size of indexes is larger? I've been told by management, we can not have any downtime, its my understanding even with online index there's a chance blocking can occur in the final phase of the index operation. My database and index size is over 1.5 tb and the number of transaction per second are in the 100's.
I try to create script which Rebuild one table index after transaction log backup.
In my script first i check or backup is complete in 10 minutes if i find record i do it index rebuild if i don't find i need go back and check again.
The problem is that query finish if don't find a backup record, How i can loop that script that he checking until find the record and then start rebuild index.
Use DB GO DECLARE @database_name NVARCHAR(50) SELECT @database_name='DB'`
START: WHILE EXISTS (SELECT msdb.dbo.backupset.database_name,