Wednesday, March 7, 2012

returning values from sp_executesql statements

I'm trying to return a set the value of a variable with the output from a sp_executesql statement, but I'm not sure how to do it. Basically, what I want to do is:

set @.sql = 'select time from ' + @.tablename + ' where id = ' + @.int

How do I go about doing this?I don't understand why do you need sp_executesql for that
You can use a simple SQL statement like:

select @.return_value = time from your_table where id = @.int

or

select @.return_value = (select time from your_table where id = @.int)

Originally posted by dez182
I'm trying to return a set the value of a variable with the output from a sp_executesql statement, but I'm not sure how to do it. Basically, what I want to do is:

set @.sql = 'select time from ' + @.tablename + ' where id = ' + @.int

How do I go about doing this?|||because the table name that I'm selecting from need to change depending on user input.|||Hi try this.

DECLARE @.ssql varchar(255)
DECLARE @.tablename varchar(40)
DECLARE @.int int

SELECT @.tablename = 'sometable'
SELECT @.int = 5
SELECT @.ssql = 'select time from ' + @.tablename
SELECT @.ssql = @.ssql + ' where id = ' + CONVERT(VARCHAR(16),@.int)

EXEC(@.ssql)

No comments:

Post a Comment