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 |
|
d4046949
Starting Member
9 Posts |
Posted - 2008-08-15 : 12:06:57
|
| Hey guess got another problem. I've build a standard sql queryselect id from table1 where id = '1'now what if i didnt want to select id? What if i wanted to get the user to decide what table to select?I've tried setting a varaible and doing this:select @id from table1 where @id = @interestedIDbut this fails. Can anyone recommend a way??Thanks. |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2008-08-15 : 12:11:07
|
| you need to do it like thisSET @Sql='select '+ @column + ' from ' + @Table + ' where id=' + @valueEXEC(@Sql) @column,@Table & @value are values passed by you for column table & filteralso remember to declare @sql.Why do you actually want users to decide table? |
 |
|
|
Transact Charlie
Master Smack Fu Yak Hacker
3451 Posts |
Posted - 2008-08-15 : 12:14:37
|
| Try and avoid doing things like this if you can.If you have a choice of a set number of tables that's not stupidly big then it's probably better to write a parametrised stored procedure and perform an IF statement separated select inside it rather than building a query dynamically.It might seem like more work to start off with but trust me, it is far easier to maintain in the long run (and a lot more efficient).-------------Charlie |
 |
|
|
Transact Charlie
Master Smack Fu Yak Hacker
3451 Posts |
Posted - 2008-08-15 : 12:16:19
|
| And, even if you *do* decide that you want to do this dynamically I'd recommend the stored procure anyway as a wrapper. That way you can parse the parameters passed to it in a controlled way and protect yourself from sql injection.-------------Charlie |
 |
|
|
madhivanan
Premature Yak Congratulator
22864 Posts |
Posted - 2008-08-18 : 04:20:39
|
| Also make sure to read thiswww.sommaarskog.se/dynamic_sql.htmlMadhivananFailing to plan is Planning to fail |
 |
|
|
|
|
|