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
 General SQL Server Forums
 New to SQL Server Programming
 My Variable in sql statement

Author  Topic 

pamyral_279
Posting Yak Master

143 Posts

Posted - 2006-08-11 : 02:58:43
Declare @MyCode nvarchar(20);
Set @MyCode='ABC'
set @int_rowcount=(SELECT count(hoten) FROM @MyCode)
I run it but still errors !
How can i implement above statement ?
Thank you very much !

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2006-08-11 : 03:01:15
you can't use a variable for table name
if you need to you have to use Dynamic SQL like exec() or sp_executesql. Check out the detail in Books On Line


KH

Go to Top of Page

pamyral_279
Posting Yak Master

143 Posts

Posted - 2006-08-11 : 04:00:44
I need to run "select count(*) from table" and get the result.
And then assign result of above statement into variable !
My problem : Table in above statement is variable.
how can i write sql ?
Thank you very much.
quote:
Originally posted by khtan

you can't use a variable for table name
if you need to you have to use Dynamic SQL like exec() or sp_executesql. Check out the detail in Books On Line


KH



Go to Top of Page

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2006-08-11 : 04:03:13
then you have to use sp_exeuctesql

try this

declare @sql nvarchar(4000)
select @sql = N'select @int_rowcount = count(hoten) from ' + @MyCode
exec sp_executesql @sql, N'@int_rowcount int OUTPUT', @int_rowcount OUTPUT


EDIT : Typo error in red

KH

Go to Top of Page

pamyral_279
Posting Yak Master

143 Posts

Posted - 2006-08-11 : 04:27:25
Sorry when i do your guide :
It's display errors:
Unclosed quotation mark before the character string '@int_rowcount int OUTPUT), @int_rowcount OUTPUT

quote:
Originally posted by khtan

then you have to use sp_exeuctesql

try this

declare @sql nvarchar(4000)
select @sql = N'select @int_rowcount = count(hoten) from ' + @MyCode
exec sp_executesql @sql, N'@int_rowcount int OUTPUT), @int_rowcount OUTPUT



KH



Go to Top of Page

KenW
Constraint Violating Yak Guru

391 Posts

Posted - 2006-08-11 : 12:06:04
pamyral,

KH fixed the error in the post just above your last one.

Ken
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2006-08-11 : 12:11:46

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

Madhivanan

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

- Advertisement -