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
 Building a dnymaic query

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 query

select 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 = @interestedID

but 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 this

SET @Sql='select '+ @column + ' from ' + @Table + ' where id=' + @value
EXEC(@Sql)

@column,@Table & @value are values passed by you for column table & filter
also remember to declare @sql.
Why do you actually want users to decide table?
Go to Top of Page

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
Go to Top of Page

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
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2008-08-18 : 04:20:39
Also make sure to read this
www.sommaarskog.se/dynamic_sql.html

Madhivanan

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

- Advertisement -