What is a “batch”, and why is GO used?

GO is not properly a TSQL command. Instead it’s a command to the specific client program which connects to an SQL server (Sybase or Microsoft’s – not sure about what Oracle does), signalling to the client program that the set of commands that were input into it up till the “go” need to be sent … Read more

T-SQL Decimal Division Accuracy

For multiplication we simply add the number of decimal places in each argument together (using pen and paper) to work out output dec places. But division just blows your head apart. I’m off to lie down now. In SQL terms though, it’s exactly as expected. –Precision = p1 – s1 + s2 + max(6, s1 … Read more

Select query to remove non-numeric characters

See this blog post on extracting numbers from strings in SQL Server. Below is a sample using a string in your example: DECLARE @textval NVARCHAR(30) SET @textval=”AB ABCDE # 123″ SELECT LEFT(SUBSTRING(@textval, PATINDEX(‘%[0-9.-]%’, @textval), 8000), PATINDEX(‘%[^0-9.-]%’, SUBSTRING(@textval, PATINDEX(‘%[0-9.-]%’, @textval), 8000) + ‘X’) -1)

How can I use optional parameters in a T-SQL stored procedure?

Dynamically changing searches based on the given parameters is a complicated subject and doing it one way over another, even with only a very slight difference, can have massive performance implications. The key is to use an index, ignore compact code, ignore worrying about repeating code, you must make a good query execution plan (use … Read more

How to get sp_executesql result into a variable?

If you have OUTPUT parameters you can do DECLARE @retval int DECLARE @sSQL nvarchar(500); DECLARE @ParmDefinition nvarchar(500); DECLARE @tablename nvarchar(50) SELECT @tablename = N’products’ SELECT @sSQL = N’SELECT @retvalOUT = MAX(ID) FROM ‘ + @tablename; SET @ParmDefinition = N’@retvalOUT int OUTPUT’; EXEC sp_executesql @sSQL, @ParmDefinition, @retvalOUT=@retval OUTPUT; SELECT @retval; But if you don’t, and can … Read more