Sunday, February 26, 2012

Get result from EXEC()

I currently do this:
INSERT INTO #tbl2 EXEC(@.sql)
IF @.@.ROWCOUNT = 1
INSERT INTO @.tbl3 SELECT userID FROM #tbl2
DELETE FROM #tbl2
Is there any other way to recieve the result from column userid from the @.sql-query?Hi,

try to use sp_executesql (see BOL):

sp_executesql [@.stmt =] stmt
[
{, [@.params =] N'@.parameter_name data_type [,...n]' }
{, [@.param1 =] 'value1' [,...n] }
]

Markus|||How do you mean?|||Hi,

i don't know what you really want to query, but here an (quick and dirty) example:

-- testing enviroment
create table usernames( userid int, username varchar(100) )
insert into usernames (userid,username) values ( 123, 'moby' )
insert into usernames (userid,username) values ( 986, 'lars' )
-- select * from usernames
--
-- vars
declare @.Stmt nvarchar(200), @.UserID int, @.UserName varchar(100)
-- SQL-Stattement to get result from
select @.Stmt='select @.P1= userid from usernames where username=@.P2'
-- "input" parameter
select @.Username='moby'
-- query result
exec sp_executesql @.Stmt, N'@.P1 int output, @.P2 varchar(100)', @.P1=@.UserID output, @.P2=@.Username
-- show result
print @.Username
print @.UserID

-- get rid of testdata
drop table usernames|||Thank you!

No comments:

Post a Comment