Unique key vs. unique index on SQL Server 2008

A unique constraint is implemented behind the scenes as a unique index, so it doesn’t really matter how you specify it. I tend to implement it simply as: ALTER TABLE dbo.foo ADD CONSTRAINT UQ_bar UNIQUE(bar); Some people create a unique index instead, e.g. CREATE UNIQUE INDEX IX_UQ_Bar ON dbo.foo(bar); The difference is in the intent … Read more

“This SqlTransaction has completed; it is no longer usable.”… configuration error?

I believe this error message is due to a “zombie transaction”. Look for possible areas where the transacton is being committed twice (or rolled back twice, or rolled back and committed, etc.). Does the .Net code commit the transaction after the SP has already committed it? Does the .Net code roll it back on encountering … Read more

How to rewrite IS DISTINCT FROM and IS NOT DISTINCT FROM in SQL Server 20008R2?

The IS DISTINCT FROM predicate was introduced as feature T151 of SQL:1999, and its readable negation, IS NOT DISTINCT FROM, was added as feature T152 of SQL:2003. The purpose of these predicates is to guarantee that the result of comparing two values is either True or False, never Unknown. These predicates work with any comparable … Read more

Using IF ELSE statement based on Count to execute different Insert statements

Depending on your needs, here are a couple of ways: IF EXISTS (SELECT * FROM TABLE WHERE COLUMN = ‘SOME VALUE’) –INSERT SOMETHING ELSE –INSERT SOMETHING ELSE Or a bit longer DECLARE @retVal int SELECT @retVal = COUNT(*) FROM TABLE WHERE COLUMN = ‘Some Value’ IF (@retVal > 0) BEGIN –INSERT SOMETHING END ELSE BEGIN … Read more

Connecting to MS SQL Server with Windows Authentication using Python?

You can specify the connection string as one long string that uses semi-colons (;) as the argument separator. Working example: import pyodbc cnxn = pyodbc.connect(r’Driver=SQL Server;Server=.\SQLEXPRESS;Database=myDB;Trusted_Connection=yes;’) cursor = cnxn.cursor() cursor.execute(“SELECT LastName FROM myContacts”) while 1: row = cursor.fetchone() if not row: break print(row.LastName) cnxn.close() For connection strings with lots of parameters, the following will accomplish … Read more