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

learn more… | top users | synonyms

1
vote
2answers
1k views

Options for keeping two SQL Server Compact databases in sync?

Developer here. I have a system where there is a front machine creating rows in a moderately complex database, and a back machine that must sync with the front machine to run reports. Both run SQL ...
1
vote
1answer
862 views

Trying to Build TreeView Query in T-SQL

I have parent records in two tables, Table1 and Table2. Some records in Table3 are children of Table1, and some are children of Table2. I would like to build a query that I can use to populate a ...
4
votes
2answers
2k views

Query two SQL Server databases in same function but on two different servers

Suppose I have two database servers (DB-SERVER-1 & DB-SERVER-2), and there is a single database on each server (DB1 & DB2). Both are SQL Server databases. Is it possible to query both ...
4
votes
2answers
362 views

T-SQL Syntax error copying views dynamically

I'm creating a stored procedure to copy all views from one database to another using the following code. ALTER PROCEDURE [dbo].[spCreateViews] (@SourceDB NVARCHAR(200), @DestinationDB ...
6
votes
1answer
484 views

CATCH block is triggered when it should not

On my neverending quest for shooting myself in the foot with save transaction I seem to have found even more ways to fulfill the quest purpose. The save transaction clause itself this time is out of ...
5
votes
3answers
1k views

Total of orders open on a given date for each date in a date range

This question is similar to Running total with count?, but please allow me to explain some further twists on the issue. I'm using SQL Server 2008, so the cursor option described by Aaron Bertrand ...
2
votes
2answers
5k views

SQL Server : how to drop all constraints on a table in T-SQL

I´d like to drop all constraints on all tables in my database, because I need to change the relationships of many of the tables. Is there any way to do that with T-SQL? I cannot find any solution ...
3
votes
1answer
2k views

How to remove xmlns from child elements with FOR XML

I have a TSQL query that I use to generate a SOAP document. I am using two namespaces. Namely: - http://schemas.xmlsoap.org/soap/envelope/ for "packaging" the soap document - A custom one that ...
6
votes
5answers
32k views

Writing select result to a csv file

We need to write the SELECT query results to a csv file. How can it be done using T-SQL in SQL Server 2008 r2? I know that it can be done in SSIS, but for some reasons, we don't have this option. I ...
7
votes
3answers
4k views

SQL Server 2008 merge statement deadlocking itself

I have the following procedure (SQL Server 2008r2): create procedure usp_SaveCompanyUserData @companyId bigint, @userId bigint, @dataTable tt_CoUserdata readonly as begin set ...
6
votes
3answers
3k views

RETURN statement before DEALLOCATE CURSOR

Question about use of Cursors in combination with RETURN in a SQL Server 2008 Stored Procedure Consider this example: CREATE PROCEDURE [dbo].[test] @ReturnEarly BIT = 0 AS BEGIN SET NOCOUNT ...
2
votes
1answer
568 views

Rules in SQL Server 2005

The syntax for rules in SQL Server 2005 is given: CREATE RULE [ schema_name . ] rule_name AS condition_expression Whenever using rule, for example: CREATE RULE list_rule AS @list IN ('1389', ...
4
votes
1answer
2k views

T-SQL: Convert XML to string without self-closing tags

We have a weirdo system we're integrating with which consumes XML, but it does not understand self-closing tags, so <BOOKING> <BOOKINGID>56812</BOOKINGID> <PERSONCODE /> ...
1
vote
1answer
262 views

SQL Server 2008 R2 - Weekly / Monthly Statistics

I'm new working with SQL Server 2008 R2 Express, and I´d like to gather some statistics every week / month for users who are connecting to this server. For instance, how many times they were ...
4
votes
2answers
410 views

Escaping T-SQL Keywords

$sql = "SELECT Kill FROM tbl_pvporderview"; Problem is that I end up with: Incorrect syntax near the keyword 'Kill'. Because kill is a T-SQL command... any way to bypass it? I can't change the ...
1
vote
1answer
162 views

EXISTS and sub-query cost

i've just wondered if there's a difference in cost(memory,cpu) of an EXISTS or NOT EXISTS in following queries. Does it make a difference if i select NULL, 1 or columns? 1) SELECT id FROM Parent p ...
3
votes
1answer
151 views

Selecting 'edge' records in a sequence of data

I have a table of items which run sequentially by date with both a start and end for each entry: ID | Start | End ---------------------------------------- 1 | 2012-08-20 00:00 | ...
8
votes
2answers
186 views

Non-Clustered Indexes - keys and nonkeys

I just want to make sure I'm on the right track with these concepts, so any feedback would be greatly appreciated. Here's my theory from the query I've just optimised, through a process of trial and ...
6
votes
4answers
3k views

T-SQL command to log in as a different user?

Is there a T-sql command, like the Oracle "Connect" which lets me change the user that I am logged in as?
5
votes
4answers
924 views

Speeding up COUNT(*) - WHERE clause slowing query

The following query takes 497 ms to run, if I remove the AND portion onwards it only takes 320 ms. Is there any way to speed this up? The only indexes I have on 'messages' table is a PK on ...
2
votes
2answers
440 views

Make sure two columns are sorted in the same order

I have a table like this: CREATE TABLE T ( ID INT NOT NULL IDENTITY PRIMARY KEY, CreateDateTime datetime2 NOT NULL, --other columns ) How can I make sure that ID and CreateDateTime are both ...
0
votes
6answers
630 views

Equivalent of CHARINDEX OR IN for ints

I want the equivalent of this for ints. --Valid SQL DECLARE @users AS nvarchar(50) SET @users = 'Joe ,Bob,Fred,Tim' --1,2,8,23 select * FROM Person AS p WHERE CHARINDEX(p.sFullName,@users) > 0 ...
7
votes
1answer
83 views

sysschedules datatype choices

I am Curious. Why does TSQL save the values in msdb.dbo.sysschedules for date and times as ints instead of using datetime. I assume the reason dates back to something in SQL Server 2000. Was it a ...
2
votes
3answers
8k views

Questions about handling NULLs and empty strings in nvarchar and numeric fields

I understand that questions similar to these pop up often around here. I have searched before posting these but I didn't find any QA threads that completely answer my questions. In a table, I ...
4
votes
1answer
2k views

SQL Server 2012 is putting [brackets] around Table and Column Names

Is there anyway to turn that off? I'm unable to find anything in options, and they're really a distraction.
3
votes
1answer
2k views

sp_execute expects parameter '@handle' of type 'int'

I'm trying to check in a stored procedure if a table exists in my destination database. If it does not then I will create the table useing the information_schema tables from the source database. ...
2
votes
2answers
1k views

Is there any way to speed up a query with 3x UNION on the same large table?

Assuming that the following query is legitimate and executes successfully, is there any way to speed it up? SELECT foo from T1 --T1 is a huge (>5e6 rows) table with no indexes UNION SELECT bar ...
10
votes
2answers
1k views

Why does SELECT 1/2 return 0?

As the title says. I even tried SELECT CONVERT(NUMERIC, 1/2) which also returned 0. I am using SQL Server 2008.
2
votes
2answers
928 views

Bulk grant execute permissions for scalar functions & stored procedures

We have a situation where we have restored a large number (50+) of MSSQL2008 databases from backup and most if not all of them require that a user is granted EXECUTE permissions on scalar functions ...
13
votes
2answers
2k views

Why do wildcards in GROUP BY statements not work?

I am trying to make the following SQL statement work, but I get a syntax error: SELECT A.*, COUNT(B.foo) FROM TABLE1 A LEFT JOIN TABLE2 B ON A.PKey = B.FKey GROUP BY A.* Here, A is a wide table ...
5
votes
2answers
9k views

How can I strip non-numeric characters out of a string?

Users enter a search term in a box, and that value gets passed to a stored procedure and checked against a few different fields in the database. These fields are not always of the same data type. One ...
7
votes
1answer
3k views

Should I add SET NOCOUNT ON to all my triggers?

It is fairly common knowledge that you should have SET NOCOUNT ON by default when creating new stored procedures. Microsoft has changed the default template to include this in 2012. I thought ...
4
votes
4answers
11k views

T SQL Table Valued Function to Split a Column on commas

I wrote a Table Valued Function in Microsoft SQL Server 2008 to take a comma delimited column in a database to spit out separate rows for each value. Ex: "one,two,three,four" would return a new table ...
8
votes
2answers
582 views

How does SQL Server store the information in Job Schedule Properties?

I know there is SELECT * FROM msdb..sysjobschedules, but that just shows the next time a job is scheduled to run. I want to know how this is all determined and stored. So where does it store the ...
9
votes
2answers
3k views

SQL Server Decimal(9, 0) vs INT

One of our customers uses for some columns the datatype DECIMAL(18,0) in his SQL Server 2008R2 database. Because the columns grow quite slowly, he recently proposed to change the datatype to ...
10
votes
2answers
3k views

Good way to call multiple SQL Server Agent jobs sequentially from one main job?

I've got several SQL Server Agent jobs that should run sequentially. To keep a nice overview of the jobs that should execute I have created a main job that calls the other jobs with a call to EXEC ...
2
votes
0answers
402 views

SQL Server : where with cast(value as varbinary) vs cast(value as varbinary(300))

Are there any theoretical performance differences between these queries in the scenarios below. Scenarios are: MyTable has Value nvarchar(300) MyTable has Value nvarchar(max) Q1: declare @p ...
2
votes
2answers
510 views

Reorganize Indexes T-SQL

I'm moving a database to SQL Azure and with that I lose the maintenance plans so I am going to use a Worker Role to schedule them. When I open the properties of the Rebuild Index Task and click on ...
3
votes
2answers
126 views

When did a specific database come online?

How can I determine when the state of a specific database switched to online? Background: I want to determine how long the database is in use to find out how reliable sys.dm_db_index_usage_stats ...
10
votes
5answers
1k views

UPDATE with JOIN on 100mm records, how to do this better? (in T-SQL)

I need to update 100 million records in a single table, in effect, normalizing the table by replacing the varchar value of a column with simply an ID. (I say "replacing" but really I'm writing the ID ...
3
votes
1answer
612 views

DENY EXECUTE on one schema object hides other objects in same schema

I have five stored procedures in a schema [XTR], the users are all in one AD group [AD\Users] and have db_datareader and public assigned to them. On one of the stored procedures I don't want to give ...
4
votes
1answer
1k views

Using FLOATs with RAISERROR

I am using RAISERROR() to provide some basic Unit Testing functionality (as here), but I am frustrated by the inability to use FLOATs in the error message. I know I can cast the float to a string, but ...
2
votes
1answer
758 views

Can I Rebuild indexes in a DB except for one table?

I have a table in my database that is constantly monitored by an application server for changes. Unfortunately rebuilding the indexes connected with this table breaks the app server's connection. This ...
4
votes
2answers
6k views

A Script to insert dummy Data in all tables of Database

I wanted a Script that can loop through all tables and their columns in the database and insert dummy data based on column type and size, so that i can start using the database for testing, and ...
2
votes
1answer
1k views

Looking for a Trigger to change inserting strings?

I have an MSSQL Server 2008 Database. There are some tables in my Database like below : table1, table2, table3, .... each table has a NVARCHAR(50) field (Name) Now, I wanna change the strings that ...
1
vote
1answer
426 views

Return a percentage of the full record set

I'm pulling back a list of orders but I need to only display a percentage of the records. for example we want the top 30 or top 50. The percentagbe is variable so I'd like to not use TOP. I tried ...
1
vote
1answer
810 views

bitwise operators effecting performance

I have recently seen some stored procs coming my way that contain BITWISE operators that are causing the optimizer problems. I know from playing with execution plans that these are the cause of the ...
5
votes
4answers
14k views

Add a new Column and define its position in a table

I have Table A with 5 columns: TableA -- Name Tel Email Address I want to add a new column (mobile) in between Tel & Email: TableA -- Name Tel Mobile Email Address If I use ALTER TABLE ...
2
votes
2answers
523 views

Design best practices for last tracking with indexed view

My tables structure is below : TbDoc (ID int , ...) TbDocActions( ID Int, DocID Int, Date DateTime, col1 int, col2 int, ...) I want to have indexed view to get last TbDocActions columns for ...
3
votes
2answers
5k views

Create new function by code if it doesn't exist

I want to create new function by script in my database. The script code is below: IF Exists(Select * From sys.sysobjects A Where A.name =N'fn_myfunc' and xtype=N'FN') return; CREATE FUNCTION ...