0

My procedure returning nothing when pass where clause condition as parameter. Below is the example query and I am passing @strWhereClauseField & @strWhereClauseValue as a parameter. It works fine when I convert my query in string and execute it. But I don't want to use query string because order by is not working in query string.

DECLARE @Data TABLE
(
     Id int identity(1,1), Product varchar(10)
)

INSERT @Data VALUES ('HP2030'), ('HP2031'), ('HP2032'), ('HP2033');

DECLARE @strWhereClauseField NVARCHAR(1000) = '1'
DECLARE @strWhereClauseValue NVARCHAR(1000) = '1'

SET @strWhereClauseField = '@Data.Product'
SET @strWhereClauseValue = '''HP2030'''

SELECT * 
FROM @Data 
WHERE @strWhereClauseField = @strWhereClauseValue
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
user1891251
  • 41
  • 1
  • 1
  • 12

2 Answers2

0

Unfortunately what you are doing will not work in SSMS (SQL Server Management Studio) as SSMS sees the query as so:

SELECT * FROM @Data WHERE '@Data.Product' = '''HP2030'''

Try the following:

DECLARE @Data TABLE
(
     Id int identity(1,1), Product varchar(10)
)

INSERT @Data VALUES ('HP2030'), ('HP2031'), ('HP2032'), ('HP2033');

DECLARE @strWhereClauseField NVARCHAR(1000) = '@Data.Product'
DECLARE @strWhereClauseValue NVARCHAR(1000) = '''HP2030'''
DECLARE @strOrderByColumn NVARCHAR(1000) = 'Product'


DECLARE @sql VARCHAR(MAX) = 'SELECT * FROM @Data WHERE ' + @strWhereClauseField + '=' + @strWhereClauseValue + ' ORDER BY ' + @strOrderByColumn

EXEC sp_executesql(@sql)
user7351608
  • 441
  • 2
  • 10
  • Just `EXEC(@sql)` You also have a problem that the scope in which `EXEC(@sql)` runs doesn't have access to the table variable. You'll need to use a more 'accessible' table or wrap table declaration and loading into `@sql` Finally `@WhereClauseField == '@Data.Product'` doesn't work. Either drop the table prefix or use an alias. – Disillusioned Dec 30 '16 at 08:55
0

Try this:

DECLARE    @strWhereClauseField NVARCHAR(1000) = '1'
DECLARE     @strWhereClauseValue NVARCHAR(1000) = '1'
DECLARE @QUERY VARCHAR(MAX)

SET @strWhereClauseField='Product'
SET @strWhereClauseValue='''HP2030'''

SET @QUERY = 'DECLARE @Data TABLE
(
 Id int identity(1,1)
,Product varchar(10)
 )
INSERT @Data VALUES
(''HP2030'');
INSERT @Data VALUES
(''HP2031'');
INSERT @Data VALUES
(''HP2032'');
INSERT @Data VALUES
(''HP2033'');
SELECT * FROM @Data WHERE '+@strWhereClauseField+'='+@strWhereClauseValue+''
EXEC (@QUERY)
Ranjana Ghimire
  • 1,785
  • 1
  • 12
  • 20