TSQL - 如果记录存在于单个选择中,则将查询中的值分配给变量

时间:2013-05-16 07:47:57

标签: sql sql-server-2008 tsql

如何改进以下代码才能使用'select'一次?

IF EXISTS (SELECT [NUMBER] FROM [TABLE] WHERE [ID_RECORD] = @id_record
BEGIN
   DECLARE @tmp_variable
   SELECT @tmp_variable = [NUMBER] FROM [TABLE] WHERE [ID_RECORD] = @id_record

   SET @other_variable = @tmp_variable
END
ELSE
BEGIN
   SET @other_variable = 0
END

2 个答案:

答案 0 :(得分:18)

试试这个:

 DECLARE @tmp_variable INT
 SET @tmp_variable = ISNULL(( SELECT    [NUMBER]
                              FROM      [TABLE]
                              WHERE     [ID_RECORD] = @id_record
                             ), 0)

答案 1 :(得分:6)

试试这个解决方案:

DECLARE @tmp_variable int
SET @tmp_variable = null
SELECT @tmp_variable = [NUMBER] FROM [TABLE] WHERE [ID_RECORD] = @id_record

IF @tmp_variable is not null
BEGIN           
   SET @other_variable = @tmp_variable
END
ELSE
BEGIN
   SET @other_variable = 0
END