Sunday, March 11, 2012

Custom query string question

Hi there,

I have a custom query string that I placed as a varchar, for instance

@.UnknownColumnName varchar(100)
@.CostumQueryString varchar(1000)
@.Value int

SET @.UnknownColumnName = (SELECT ColName FROM Utility WHERE ID =1)

SET @.CustomQueryString = 'SELECT ' + @.UnknownColumnName + ' From Table2 WHERE .....'

I have to execute this custom querystring now:
SET @.Value = (EXEC sp_executesql @.CustomQueryString)

I get a syntax error....I'm not sure how i can execute this querystirng and set the result to a variable..any help much appreciated

Regards
Mike

you can try this one

SET @.CustomQueryString = 'SELECT ' + @.UnknownColumnName + ' INTO #Values From Table2 WHERE .....'

EXEC sp_executesql @.CustomQueryString

SELECT *
FROM #Values

DROP TABLE #Values|||Hi, thanks for the reply.

I actually found the solution in books online (ooops should have searched harder there) and the best way of doing this is to make use of OUTPUT parameters:

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;

No comments:

Post a Comment