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

Our new SQL Server Forums are live! Come on over! We've restricted the ability to create new threads on these forums.

SQL Server Forums
Profile | Active Topics | Members | Search | Forum FAQ
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Quoting in a @sql help
 Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

Starting Member

4 Posts

Posted - 06/25/2014 :  09:40:22  Show Profile  Reply with Quote

Not sure title is right but I have a normal query which is roughly:

select * from table where
host in ('machine1', 'machine2')

I want to create a dynamic query where the table name changes but the rest is the same. I'm having trouble working out how to do the IN statement as the quotes cause syntax errors:

SET @sql ' select*from '+@table+' where host in ????? ' exec (@sql)

So the only dynamic bit is the table.

Any help is appreciated!

Flowing Fount of Yak Knowledge

8781 Posts

Posted - 06/25/2014 :  09:43:23  Show Profile  Visit webfred's Homepage  Reply with Quote
Escaping the single quotes with another single quote but not the needed first and last...

SET @sql ' select * from '+@table+' where host in (''machine1'', ''machine2'')'

Too old to Rock'n'Roll too young to die.
Go to Top of Page

Starting Member

4 Posts

Posted - 06/25/2014 :  10:22:29  Show Profile  Reply with Quote
Nice works, thanks a lot!
Go to Top of Page
  Previous Topic Topic Next Topic  
 Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.03 seconds. Powered By: Snitz Forums 2000