How do I fetch multiple columns for use in a cursor loop?

Here is slightly modified version. Changes are noted as code commentary. BEGIN TRANSACTION declare @cnt int declare @test nvarchar(128) — variable to hold table name declare @tableName nvarchar(255) declare @cmd nvarchar(500) — local means the cursor name is private to this code — fast_forward enables some speed optimizations declare Tests cursor local fast_forward for SELECT … Read more

How do I drop a function if it already exists?

IF EXISTS ( SELECT * FROM sysobjects WHERE id = object_id(N’function_name’) AND xtype IN (N’FN’, N’IF’, N’TF’) ) DROP FUNCTION function_name GO If you want to avoid the sys* tables, you could instead do (from here in example A): IF object_id(N’function_name’, N’FN’) IS NOT NULL DROP FUNCTION function_name GO The main thing to catch is … Read more

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

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

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)