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.
| Author |
Topic |
|
anik5
Starting Member
6 Posts |
Posted - 2006-11-01 : 10:26:13
|
Hi,I am trying to create a dynamic SQL statment by passing in values from variables. For example:declare @field1 varchar(10)declare @field1 varchar(10)declare @cmd varchar(1000)Set @field1 = 'South Pole'Set @field2 = 'Winter'-- An exmaple of a SQL statement to be created is :Select 'South Pole','Winter', count(*) from Penguines, ##tmp1 where Penguines.type = ##tmp1.type-- Please note that the above is not a real example. The key is how do I get the values South Pole and Winter inside of single quotesso that the constructed value od @cmd is the same as given in the above example.Set @cmd = 'Select ' + How do I proceed after this? I tried different combinations of single an ddouble quotes, but SQL Server is not liking it.Thanks for your help in advance! |
|
|
madhivanan
Premature Yak Congratulator
22864 Posts |
Posted - 2006-11-01 : 10:32:17
|
| Select ''South Pole'',''Winter'', count(*) from Penguines, ##tmp1 where Penguines.type = ##tmp1.typeorSet @cmd ='Select '''+@field1+''','+@field2+'',' count(*) from Penguines, ##tmp1 where Penguines.type = ##tmp1.type'Note that i didnt test second exampleMadhivananFailing to plan is Planning to fail |
 |
|
|
khtan
In (Som, Ni, Yak)
17689 Posts |
Posted - 2006-11-01 : 10:34:08
|
[code]Set @cmd = 'Select ''' + @filed1 + ''', ''' + @field2 + ''',' count(*) from Penguines, ##tmp1 where Penguines.type = ##tmp1.type'[/code]specify 2 double quote for each single quote inside the quoted string KH |
 |
|
|
anik5
Starting Member
6 Posts |
Posted - 2006-11-01 : 10:49:00
|
| Thanks for all the response Guys. I just had to make one change :Set @cmd = ' select ''' +@field1 +''',''' + @field2 +''', count(*) from Penguines, ##tmp1 where Penguines.type = ##tmp1.type'Removed the quote before the count(*) |
 |
|
|
madhivanan
Premature Yak Congratulator
22864 Posts |
Posted - 2006-11-01 : 20:28:05
|
| Also referwww.Sommarskog.se/dynamic_sql.htmlMadhivananFailing to plan is Planning to fail |
 |
|
|
|
|
|
|
|