Thursday, April 2, 2009

EXECUTE sp_executesql

DECLARE @IntVariable int;
DECLARE @SQLString nvarchar(500);
DECLARE @ParmDefinition nvarchar(500);
DECLARE @max_title varchar(30);

SET @IntVariable = 197;
SET @SQLString = N'SELECT @max_titleOUT = max(Title)
FROM AdventureWorks.HumanResources.Employee
WHERE ManagerID = @level';
SET @ParmDefinition = N'@level tinyint, @max_titleOUT varchar(30) OUTPUT';

EXECUTE sp_executesql @SQLString, @ParmDefinition, @level = @IntVariable, @max_titleOUT=@max_title OUTPUT;
SELECT @max_title;

Here @SQLString is the dynamic query where you have 2 variables --- @level and @max_titleOUT. The variable @level is going into the dynamic query and @max_titleOUT is coming out from the dynamic query.

@ParamDefinition is the string where we must declare all the variables that will be used in the dynamic query. Look that the @max_titleOUT is set as output.

After that we have to mention which variable outside the dynamic query will give the value for @level and which variable outside the dynamic query will hold the value from @max_titleOUT. So we are assigning

@level = @IntVariable, @max_titleOUT=@max_title OUTPUT

Where @IntVariable and @max_title is the variable declared outside dynamic query. So @level will take the value from @IntVariable and will be used inside the dynamic query.
@max_title is the variable where we will get the value out from the dynamic query.

Pretty tuff huh, but no way. This is a very advanced feature of sql server. Hope you like this.

No comments: