
SQL Tips
Originally published on my old blog at cumps.be on November 29, 2007.
Various SQL-oriented tips discovered during work, written down to remember them.
BCP
Export data to a file:
bcp <dbname>..<tablename> out <filename>.dat /S<servername> /T /E /t# /cbcp "<select query, with <dbname>..<tablename>>" queryout <filename>.dat /S<servername> /T /E /t# /c
Import data from a file:
sqlcmd -Q"DELETE FROM <tablename>" -S<servername> -d<dbname> -Ebcp <dbname>..<tablename> in <filename>.dat /S<servername> /T /E /t# /c
Comma Separated List
Generate a comma-separated list of values in a table:
DECLARE @list NVARCHAR(MAX);
SELECT @list = COALESCE(@list + ',', '') + <column> FROM <table>;
PRINT @list;
Prevent Table Lock Escalation
Prevent the database from taking an exclusive table lock:
BEGIN TRANSACTION;
SELECT * FROM <table> WITH (XLOCK, HOLDLOCK) WHERE 1 = 2
Run this in a separate thread without doing a commit. It will prevent the database from escalating key/page locks to table locks.
Links
You May Also Like

Efficient Compound Index Usage
How the column order of a compound index decides between an index seek and a full scan, tested on a 6.5 million row table in SQL Server.

Search File Contents
Windows Search can look inside files, but by default not inside .sql or .php files. One registry key per extension fixes that.

Extracting Stored Procedure Content via SQL
Three SQL Server queries to list databases, list user stored procedures and read a procedure's source from syscomments.



