SQL局部变量

时间:2011-08-10 07:11:24

标签: sql-server-2005 local-variables isnull select-case insert-select

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

2 个答案:

答案 0 :(得分: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'

答案 1 :(得分:1)