Вопрос

I use SQL Server 2005 and I have a query like this :

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'

This works fine. It inserts values inside [subject] table, The first value [sch_id] is taken from [schedule] table through a searched CASE statement.

I want to avoid code redundancy, so I tried to store the result of the SELECT statement in a local variable and evaluate it using an ISNULL function. Looks like this :

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'

But my code doesn't work. SQL Server 2005 says the error is coming from the line where I used the local variable (@sched). What is wrong in my query?

Это было полезно?

Решение

this should tell you exactly what you need: http://msdn.microsoft.com/en-us/library/aa259186(v=sql.80).aspx

Другие советы

I think this will do what you want.

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'
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top