1

我使用 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) 的行。我的查询有什么问题?

4

2 回答 2

3

我认为这会做你想要的。

INSERT INTO [subject] ([sch_id], [subj_from], [subj_to])
SELECT (
          SELECT [sch_id]
          FROM [schedule]
          WHERE [sch_name] = 'Search Schedule Name'
       ), 
      'from value',
      'to value'
于 2011-08-10T07:20:12.110 回答
1

这应该告诉你你需要什么:http: //msdn.microsoft.com/en-us/library/aa259186 (v=sql.80).aspx

于 2011-08-10T07:15:25.150 回答