我在表中有一些任务列表,每个任务都有“已完成”列,有些任务可能已完成或未完成。在网页中,我有文本框,我们可以传递多个任务名称,我想向用户显示消息任务是否完成。在这里,如何检查用户是否传递了多个任务名称,其中一个可能已完成,另一个可能未完成。在SQL查询中怎么做?
问问题
423 次
1 回答
0
我认为您正在根据您的问题寻找一些动态 SQL。
出于此答案的目的,我假设字符串值是逗号分隔的,逗号后可能有一个空格:
-- search criteria
DECLARE @taskNames NVARCHAR(30) = 'task1, task2, task3'
--set up some dummy data
SELECT *
INTO #TasksTemp
FROM ( SELECT 1 AS ID ,
'task1' AS TaskName ,
1 AS Completed
UNION
SELECT 2 AS ID ,
'task2' AS TaskName ,
0 AS Completed
UNION
SELECT 3 AS ID ,
'task3' AS TaskName ,
1 AS Completed
UNION
SELECT 4 AS ID ,
'task4' AS TaskName ,
0 AS Completed
) t
-- dynamic sql variable
DECLARE @sql NVARCHAR(200)
-- SANITIZE input
-- cover case where comma may have space after it
SET @taskNames = REPLACE(@taskNames, ', ', ',')
-- add quote marks to seperate string values
SET @taskNames = '''' + REPLACE(@taskNames, ',', ''',''') + ''''
SET @sql = 'SELECT * FROM #TasksTemp WHERE TaskName IN (' + @taskNames + ')'
PRINT @sql
-- will rpoduce:
-- SELECT * FROM #TasksTemp WHERE TaskName IN ('task1','task2','task3')
-- run the dynamic sql
EXEC sp_executesql @sql
DROP TABLE #TasksTemp
您可能只需要调整代码以考虑不同的分隔符。
于 2015-04-23T10:59:54.233 回答