Transact-SQL (T-SQL) is a dialect of SQL used by Microsoft SQL Server and SAP's Sybase.

learn more… | top users | synonyms

0
votes
2answers
30 views

How do I get Brent Ozar's sp_BlitzIndex to run on Azure?

I downloaded the SQL Server First Aid Kit from Brent Ozar's website. When I tried to run the sp_BlitzIndex script against my master database via Microsoft Sql Server Management Studio while logged in ...
2
votes
3answers
733 views

How to get OUTPUT $action, Inserted.*,Deleted.* records in In SSIS

I was just wondering, in MERGE in T-SQL, you can output the OUTPUT $action, Inserted.* and Deleted.* records. I want to ask how can I get OUTPUT $action, Inserted.*, Deleted.* records in SSIS?
3
votes
1answer
52 views

Compound Primary Key - Index both fields?

I have a many-to-many join table between users and roles. CREATE TABLE AppUserRole ( UserId INT NOT NULL, RoleId INT NOT NULL, CONSTRAINT PK_AppUserRole PRIMARY KEY (UserId, RoleId), ...
9
votes
4answers
47k views

What's the easiest way to create a temp table in SQL Server that can hold the result of a stored procedure?

Many times I need to write something like the following when dealing with SQL Server. create table #table_name ( column1 int, column2 varchar(200) ... ) insert into #table_name execute ...
13
votes
5answers
2k views

Index performance on ON versus WHERE

I have two tables @T1 TABLE ( Id INT, Date DATETIME ) @T2 TABLE ( Id INT, Date DATETIME ) These tables have a non-clustered index on (Id, Date) And I join these tables SELECT * ...
3
votes
1answer
313 views

sp_startpublication_snapshot Parameter(s)

I am creating a stored procedure that: Restores a DB from a .bak giving the .mdf and .ldf a new name (so we have have several copies of the same DB up (If specified in the SP's parameter) Creates ...
2
votes
4answers
116 views

Effiiency of multiple OR predicates versus a single range

Say I have a SQL statement: SELECT * FROM MyTable WHERE KeyColumn1 = 1 OR KeyColumn1 = 2 OR KeyColumn1 =3 OR ... KeyColumn1 = 10 And another: SELECT * FROM MyTable ...
-1
votes
1answer
17 views

T-SQL Trying to create a trigger that uses joins across 2 server instances [on hold]

I am trying to complete a trigger on 2 instances of SQL Server. I am running MS Dynamics ERP set CRM & GP. I need to remove data from one server once an update happens to another table. I have ...
2
votes
3answers
62 views

Show all stored procedure definitions (content) for editing

Apologies if this has been asked before, the suggested 'related' questions weren't relevant and my own search turned up very little. I need to list the definitions (code) of all my stored procedures, ...
2
votes
2answers
35 views

Ensure only one of the several records for a given item has a column with true value

I have a table called Computer with columns: id NIC_name is_primary My primary key is (id, NIC_name) and is_primary is a bit field for a boolean value. I would like to ensure that for all ...
0
votes
1answer
103 views

Automate SQL Server restore from Prod to Dev

I would like to setup an automated restore job which takes the latest timestamp .bak file and restores it into the DEV instance. I currently have a job on the DEV box that uses the UNC path to the ...
0
votes
0answers
12 views

Is it possible to move more than one database object into a schema using the `ALTER SCHEMA` statement in SQL Server 2008 R2? [duplicate]

I have a TSQL Statement like this: ALTER SCHEMA FindUsedAndUnused TRANSFER dbo.UsedUnusedNotSure_the_counts; And when I try to run it with multiple TABLEs or VIEWs I receive an error; Is there ...
0
votes
1answer
25 views

How to merge consecutive record pairs over a table?

I have a table where I need to merge consecutive record pairs (when ordered by id, data and from). Note that for pairs being merged, the first row's prevfrom is NULL and the second row's nextto is ...
2
votes
1answer
84 views

Update one column based on count of records of grouped value in another column

Given a table CREATE TABLE TABLE_ITEMS ( serial_num int null, item_group int null ); INSERT INTO TABLE_ITEMS VALUES (0,1), (1,1), (2,1), (3,1), (4,1), (0,2), (1,2), (2,2), (3,2), (4,2), ...
-1
votes
1answer
39 views

How to do superscript in SQL Server 2012 query? [closed]

I am trying to change superscript in SQL query string. Example: Select 'Your submitting date is 2nd January 2016'; As above query, I want to change nd to superscript.
1
vote
2answers
186 views

Why does FETCH NEXT return second row after opening cursor?

I have a cursor declaration: DECLARE idCursor CURSOR FOR SELECT DISTINCT [id], [data] FROM #tempRemaining OPEN idCursor And the statement: SELECT DISTINCT [id], [data] ...
2
votes
1answer
22 views

How to copy non clustered indexes in transactional replication

I create transactional replication ,but forget to include non clustered indexes and now my subscriber have only clustered indexes (primary key) and I want to transfer all nonclustered indexes to ...
1
vote
1answer
37 views

Strange behaviour in TSQL function (parameter with int variable or NULL behaves differently)?

I experienced very strange problem today with TSQL function. The function has several parameters (int and bit). One of the (int) is set with value NULL. When calling a function with NULL inside the ...
30
votes
1answer
19k views

MERGE a subset of the target table

I am trying to use a MERGE statement to insert or delete rows from a table, but I only want to act on a subset of those rows. The documentation for MERGE has a pretty strongly worded warning: It ...
0
votes
3answers
1k views

Error Grouping By Multiple Columns using CASE

Is it possible to group by multiple columns in a CASE statement? I get error "Incorrect syntax near ','." in below code... SELECT CASE WHEN Type = 'Test' THEN Description ELSE ...
1
vote
0answers
12 views

How can I return the full text of a document indexed in SQL Server Full-Text?

I'm using SQL Server 2014 with FileTables to store a large number of documents in different formats. The iFilters are working great, and everything is getting indexed with FTS + Semantic Search. Now ...
0
votes
1answer
16 views

How to FETCH from a cursor into a table variable?

I have a cursor defined as: DECLARE idCursor CURSOR FOR SELECT DISTINCT [id], [data] FROM #tempTable And I have a variable defined as: DECLARE @currentId TABLE ( ...
0
votes
1answer
50 views

Breaking up long running query into batches runs fine for a while and then produces fatal error

I'm using a variation of this post which details using "careful batching" to delete records in batches from a table that contains 38MM records. The script below runs for a while and shows results ...
1
vote
1answer
40 views

Performance improvement on SQL query joining table on itself

I'm running this query on a table with approximately 20MM records in it. It's a very slow query, and I'm wondering if there's a better way to accomplish this that might run faster ? delete previous ...
4
votes
4answers
438 views

SQL Server - Alter table vs drop and create

Our database is SQL Server 2008 R2. We have some tables that have some varchar(500) columns that I want to switch to datetime2 or bigint. I can guarantee all the data in the columns to be switched are ...
0
votes
1answer
17 views

Create a T-sql script JOB SQL-2012 and scheduled

I would like to create a T-sql script and scheduled. My goal is create all my databases (4 databases) and when the QA or DEV team need to test something, they can use these databases. The problem is ...
0
votes
2answers
26 views

Help writing query for MS SQL Server [closed]

I need to write a MS SQL Server query statement that will generate the result set table name SUMMARY from the DETAIL table Server name: Development Database name: Test DETAIL ...
8
votes
1answer
135 views

Overcome MERGE JOIN(INDEX SCAN) with explicit single KEY value on a FOREIGN KEY

Added 7/11 The issue is deadlocks occur because of index scan during MERGE JOIN. In this case a transaction trying to get S lock on the whole index at the FK parent table, but previously another ...
2
votes
1answer
520 views

Count rows in dataset SSRS2012

I want to count the number of rows in my result DataSet, I put in my DataSet a calculated field with this expression : =CountRows("DataSet1") But I have the following error message: "The expression ...
1
vote
1answer
31 views

How to group data and write it's group id for each row?

I have sample data: CREATE TABLE #T (Name varchar(5), GroupId int NULL) INSERT INTO #T (Name) VALUES ('A'), ('A'), ('A'), ('B'), ('B'), ('C'), ('D'), ('D') Name GroupId ----- ----------- A ...
1
vote
3answers
940 views

How to escape '%' inside varchar @params for RAISERROR funcion in SQL Server 2012

How I should escape the % character in params so my RAISERROR retun my message declare @msg varchar(max) = (SELECT ' Message with % ' AS MSG) if @msg is not null begin RAISERROR (@msg ,16,1); ...
0
votes
1answer
55 views

NC Index not being used [closed]

I have a table (9mm records) with a field called filename nvarchar(max)(I didn't decide on this datatype and can't change it). I'm wanting to count how many records meet the following criteria: ...
1
vote
0answers
11 views

Extracts all characters before the 3rd occurrence of a delimiter in SQL Server 2012 [migrated]

For example the string is AL*12345*B001*1 Please help me get the result to be AL*12345*B001 (all characters before the third '*' delimiter. Below I'm using a reverse to look for the last delimiter ...
0
votes
0answers
27 views

Shrink database or DB files not reducing size even after dropping biggest table

Our MDF file was originally 550GB in size (log is just 10MB), and the biggest table we had [HourlyCounters] was 140 million rows with 580 columns (varchar[50]). It's a table with a very inefficient ...
2
votes
1answer
36 views

Powershell - SQL Server - connectionstring in loop for multiple Instances

Thisis part of a bigger script which finds DatabaseFiles on a SQL Server machine (multiple instances). Following should just return all files for 3 instances. The server is called V3000801 and ...
1
vote
1answer
27 views

Dynamic SQL in a pivot table

I was watching a video on pivot tables and got to thinking, why can't we just push in a sub query into the IN clause, instead of declaring the expected columns statically? Well, turns out you cant ...
3
votes
2answers
202 views

What is the difference between Used and Allocated space?

I am learning Database operations and I have found a couple of resources online that have given me a loose understanding, but I still couldn't explain the difference myself. Explain like I am five ...
3
votes
1answer
39 views

Execution plan for COMPUTE BY

I understand that the COMPUTE BY feature is deprecated. Out of curiosity I would like to know how the query processor executes a COMPUTE BY query. The execution plan does not contain any hint: How ...
0
votes
0answers
19 views

SYNTAX ERROR: delete from multiple tables with inner join

Sorry, but I need syntax help :( This needs to run on SQL Server 2005 + DELETE SO, ASO, ASOV, AOV FROM SYS_OPTION SO INNER JOIN ADM_SYS_OPTION ASO on SO.OPTION_ID = ASO.OPTION_ID INNER JOIN ...
5
votes
2answers
407 views

Optimize a SQL query

I have to select 2 values that were less that the given id and greater than the given id. I have tried this query but is there any better way to do it Fiddle Sql Begin declare @rootValue int ...
2
votes
3answers
180 views

No advantage of using Cross Apply or CTE over inline sub-query

I came across a query like this: SELECT (SELECT COUNT(1) FROM Orders o WHERE i.ItemId = o.ItemId) [C] FROM Items i I changed it to following ;WITH cte_count AS ( SELECT COUNT(1) c, OrderId ...
0
votes
3answers
47 views

how to set “result to text” with a tsql statement in sp?

is there any way to set "result to text" within of SP while this execute a process? a tsql stament? Thanks.
0
votes
0answers
22 views

How to Backup a Database with Specific Date Range in SQL Server 2008? [duplicate]

I have a database around 160 GB size. I want to backup the database with specific date range. Example the database contains from 2013 to until today. I want to backup database from '2015-01-01 ...
1
vote
1answer
39 views

How to separate name string by the spaces in the name in T-SQL

I have a list of names, such as: Doe John James, Doe Jane and Doe Henry Albert Sr I need to split those out into the four component parts of the name (if the name has four parts) to put each of them ...
1
vote
1answer
37 views

How to do a SELECT inside of a PIVOT

I am trying to SELECT values from a column in my database in order to perform a PIVOT on those values without hard-coding them. SELECT * FROM (SELECT ItemType, [Status] FROM ...
1
vote
0answers
22 views

Using :Connect I keep getting msg 911 - database [dbname] does not exist

I have a two part T-SQL script, the first part runs against a database on a different server, the second part is supposed to run on the local PC. I'm using SQLCMD mode and the :Connect keyword but ...
0
votes
1answer
23 views

Do i need “CHECK CONSTRAINT” when i am using “WITH CHECK ADD CONSTRAINT”

I am working on SQL Server 2008 R2, where I generated a schema-only database script using SQL Server Management Studio. The generated script is as follows: ALTER TABLE [dbo].[ConsoleServer] WITH ...
1
vote
1answer
32 views

SET ANSI_NULLS at the database level versus setting it at the table level

I have generated schema-only script for my sql server 2008 R2, here is part of it:- USE [master] GO /****** Object: Database [****] Script Date: 03/25/2015 12:17:09 ******/ CREATE DATABASE [****] ...
12
votes
1answer
850 views

How can I design a query to pause / sleep / wait for a specified amount of time?

I am testing a monitoring application against a SQL Server 2000 instance. How can I write a T-SQL query that takes an amount of time that I specify? For example, most scripting languages have ...
0
votes
2answers
49 views

how to create trigger in SQL server using two tables to find stock quantity

I have two table sales and purchase. I want to create a trigger which stores final quantity in stock table by subtracting sales table sold quantity from purchase table. There is kikkat as a name n ...