Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 EXEC result in variable

Author  Topic 

nice123ej
Starting Member

48 Posts

Posted - 2007-07-07 : 01:47:47
I want to get a singular result from EXEC function

example
-------------------------------------------
declare @sqlscript varchar(1000)
declare @i int

set @sqlscript = 'select count(*) from mytable'

set @i = exec(sqlscript)
-------------------------------------------

i know this script wont work but how can i get the count result in @i

i know i can use select @i= count(*) from mytable
but this is not what i want @sqlscript is variable and can be anything

can anyone help?!

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2007-07-07 : 03:06:01
you have to use the sp_executesql.

see http://www.sommarskog.se/dynamic_sql.html


KH
[spoiler]Time is always against us[/spoiler]

Go to Top of Page

bpgupta
Yak Posting Veteran

75 Posts

Posted - 2007-07-07 : 03:21:30
you can rewrite

declare @sqlscript varchar(1000)
declare @i int

select @i = count(*) from mytable
select @i
Go to Top of Page

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2007-07-07 : 03:27:21
That is not what OP wants
quote:
i know i can use select @i= count(*) from mytable
but this is not what i want @sqlscript is variable and can be anything




KH
[spoiler]Time is always against us[/spoiler]

Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2007-07-07 : 04:08:59
or read about sp_executesql in sql server help file

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page

nice123ej
Starting Member

48 Posts

Posted - 2007-07-07 : 11:56:50
thx sp_executesql helped
Go to Top of Page
   

- Advertisement -