我使用 SQL Server 2005,我有这样的查询:
INSERT INTO [subject] ([sch_id],
[subj_from],
[subj_to],
)
SELECT
CASE
WHEN (SELECT @sched = [sch_id]
FROM [schedule]
WHERE [sch_name] = 'Searched Schedule Name') IS NULL THEN NULL
ELSE (SELECT @sched = [sch_id]
FROM [schedule]
WHERE [sch_name] = 'Searched Schedule Name')
END
AS 'sched_search_result',
'Sample Value',
'Sample Value'
这工作正常。它在 [subject] 表中插入值,第一个值 [sch_id] 通过搜索的 CASE 语句从 [schedule] 表中获取。
我想避免代码冗余,因此我尝试将 SELECT 语句的结果存储在局部变量中,并使用 ISNULL 函数对其进行评估。看起来像这样:
DECLARE @sched INT
INSERT INTO [subject] ([sch_id],
[subj_from],
[subj_to],
)
SELECT
CASE ISNULL((SELECT @sched = [sch_id]
FROM [schedule]
WHERE [sch_name] = 'Searched Schedule Name'), 0)
WHEN 0 THEN NULL
ELSE @sched
END
AS 'sched_search_result',
'Sample value',
'Sample value'
但是我的代码不起作用。SQL Server 2005 说错误来自我使用局部变量 (@sched) 的行。我的查询有什么问题?