Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL creating a dynamic where statement?

I know this is not possible, but is there something that would work? Basically I want the where statement to be dynamic, allowing me to pass it any string, which it will be able to search upon.

Declare @search varchar(80)
set @search = 'RegionID'

Select * from TBL_TripDetails
Where @search = '1'

Thanks for your answers. After reading a few documents, I have decided to use multiple select statements instead of using dynamic sql. thanks!

like image 617
Spooks Avatar asked Apr 10 '26 06:04

Spooks


1 Answers

declare @sql nvarchar(max);
set @sql = N'select * from table where ' + quotename(@search) + N'=''1''';
exec sp_executesql @sql;

See The Curse and Blessings of Dynamic SQL

like image 102
Remus Rusanu Avatar answered Apr 11 '26 22:04

Remus Rusanu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!