I created a dictionary table with 'Condition' column where I store conditions for particular customers. Table's name is CustomerConditions:
Then I created dynamic SQL where I want to use this Condition:
declare
@TableName as nvarchar(10),
@FieldName as nvarchar(20),
@CustName as Nvarchar(50),
@Condition as NVARCHAR(MAX)
set @Condition = (SELECT o.Condition FROM CustomerConditions o WHERE o.Group = @CustName)
declare @strSQL as NVARCHAR(MAX)
SET @strSQL =
'DECLARE @FieldName as nvarchar(20),
@CustName as nvarchar(50)
;WITH NewCTE AS (
SELECT Tab1.Group, '+@FieldName+'
FROM (
SELECT
'+@Condition+' AS Group,
'+@FieldName+'
FROM '+@TableName+' as c) as Tab1)
SELECT * FROM NewCTE'
EXEC(@strSQL)
The problem is that when I pass @Condition to dynamic SQL string from column 'Condition' does not become part of SQL syntax - it's passed as expression, in the result I got:
This is not what I want. I want this 'Case WHEN...' to become part of my SQL syntax.
On the other hand when I'm not using @Condition but pass 'CASE WHEN..' explicitly then everything works well (all declared parameters works well, all is good):
;WITH NewCTE AS (
SELECT Tab1.Group, '+@FieldName+'
FROM (
SELECT
CASE WHEN '+ @FieldName +' LIKE ''XY%'' OR '+ @FieldName +' LIKE ''XYZ%'' then '''+ @CustName +''' END AS Group,
'+@FieldName+'
FROM '+@TableName+' as c) as Tab1)
So how can I pass this 'Case when' condition into dynamic SQL using parameter?


@FieldName,@TableNameand so on?