也许这不能完成(除了执行SQL字符串),我尝试了很多不同的方法,但基本上我想构建一个动态的where子句,条件的两边都是变量。
我需要类似的东西(但有效):
WHERE 0 = 0
AND (
(CASE @dateCondition
WHEN 'DateCreated' THEN DateCreated
WHEN 'DueDate' THEN DateCreated
WHEN 'CompletionDate' THEN DateCreated
END) = @dateFrom)
或者基本上
WHERE @dateCondition = @dateFrom
答案 0 :(得分:0)
我已经在前端查询中退出了几年,但通常(好吧,历史上)我会做这样的事情:
WHERE 1 = 1
AND (
(@dateCondition = 'DateCreated' AND DateCreated = @dateFrom)
OR (@dateCondition = 'DueDate' AND DueDate = @dateFrom)
OR (@dateCondition = 'CompletionDate' AND CompletionDate = @dateFrom)
)
虽然取决于我的应用程序,但我可以在代码中动态构建查询。
一如既往,请注意NULL参数。
答案 1 :(得分:0)
当然,一旦我发布问题,我就会想出来。
这是我正在使用的。如果您有更好的解决方案,请告诉我。
实际上有两个解决方案:
1
AND
CASE
WHEN @dateCondition = 'DateCreated' AND DateCreated >= @dateFrom
THEN 1
WHEN @dateCondition = 'DueDate' AND DateCreated >= @dateFrom
THEN 1
WHEN @dateCondition = 'CompletionDate' AND DateCreated >= @dateFrom
THEN 1
ELSE 0
END = 1
2
AND DateCreated >= CASE
WHEN @dateCondition = 'DateCreated'
THEN @dateFrom
ELSE DateCreated
END
等...
答案 2 :(得分:0)
假设变量是提前设置的,一种简单的方法就是编写动态查询。
DECLARE @date DATE = SELECT
CASE @dateCondition
WHEN 'DateCreated' THEN DateCreated
WHEN 'DueDate' THEN DateCreated
WHEN 'CompletionDate' THEN DateCreated
END
FROM [ . . . ]
DECLARE @sql NVARCHAR(MAX) =
'SELECT *
FROM [. . .]
WHERE
@date = @dateFrom
'
EXEC sp_executesql @sql, N'@date DATE, @dateFrom DATE', @date, @dateFrom
这有安全漏洞,所以如果变量没有明确设置,那么它就没有办法了。
答案 3 :(得分:0)
您不需要动态SQL
CASE WHEN @dateCondition ='DateCreated' AND DateCreated = @dateFrom THEN 1 ELSE 0 END = 1
OR
CASE WHEN @dateCondition ='DueDate' AND DueDate= @dateFrom THEN 1 ELSE 0 END = 1
OR
CASE WHEN @dateCondition ='CompletionDate' AND CompletionDate= @dateFrom THEN 1 ELSE 0 END = 1
或者像这样
CASE WHEN @dateCondition ='DateCreated' THEN DateCreated ELSE @dateFrom END = @dateFrom
AND
CASE WHEN @dateCondition ='DueDate' THEN DueDate ELSE @dateFrom END = @dateFrom
AND
CASE WHEN @dateCondition ='CompletionDate' THEN CompletionDate ELSE @dateFrom END = @dateFrom
取决于你是否在OR中思考,或者你在AND中思考
我个人认为在AND。