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
158 views

Print variable of same datatype

I am looking for to print two variables of same datatype I have something like this declare @one int ,@two int set @one=1 set @two=2 print @one+@two obviously it will give a result 3 but I need ...
2
votes
1answer
3k views

To use or not use ISNULL(NULLIF(Field1, ''))?

In the past I've seen use of something such as SELECT ISNULL(NULLIF(Field1, ''), 'NewValue') to tersely get a fallback value. However, since the advent of CASE in TSQL, we've favored something ...
5
votes
1answer
175 views

Can We Perform an “Up-To-The-Minute Restore” After Taking Transaction Log Backups?

The Setup: Say we have a Database in Full Recovery Mode that does a nightly Database Backup, Transaction Log Backup, and Transaction Log Shrink. Now the Transaction Log grows so quickly during the ...
6
votes
3answers
2k views

Can I change table structure in a transaction and then roll it back if there is an error?

I have some ALTER TABLE statements that I am running. Not all of them work (they are the result of running SQL Data Compare) and I want to group them in some transactions and roll back the statements ...
4
votes
2answers
856 views

Restore all applicable files in a backup device in T-SQL

I'm using SQL Server (2008 R2 in this case) and I am backing up my databases into backup devices (one per database). Every Sunday the device is overwritten with a new full backup, every night a ...
6
votes
3answers
4k views

Restrict update on certain columns. Only allow stored procedure to update those columns

I have sensitive price columns that I would like to have updated only through a stored procedure. I would like all code or manual attempts to alter values in these price columns to fail if it is not ...
5
votes
1answer
618 views

Query performance while using sqlcmd [duplicate]

Possible Duplicate: Running queries with SQLCMD vs. Running queries with SSMS I have a number of scripts that query the data from different tables and consequently update them. I have ...
1
vote
1answer
401 views

Using sys.dm_os_performance_counters and DIFF to display logins per second

PROBLEM Running my script below i can see the number of logins as an accumulated number to my instance: SELECT cntr_value AS [LoginsPerSec] FROM sys.dm_os_performance_counters WHERE ...
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
926 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
388 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 ...
7
votes
1answer
507 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 ...
7
votes
5answers
38k 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
577 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
3k 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
274 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
468 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
165 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
160 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
189 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
988 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
454 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
672 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
85 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
9k 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
3k 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
2k 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
1k 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
10k 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 ...
9
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
12k 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
653 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
412 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
542 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
130 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
638 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 ...
5
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 ...