如何将不同的选择值存储到同一个变量中

时间:2010-01-07 05:16:50

标签: sql-server-2005

是否可以将不同的选择值存储到同一个变量中?

DECLARE @cout int 

SELECT @cout= count(*) FROM Master1 WHERE (...)

SET @cout = SELECT count(*) FROM Master2 WHERE (...)

SET @cout = SELECT count(*) FROM Master3 WHERE (...)

IF(@cout = 0)
 BEGIN
 END

3 个答案:

答案 0 :(得分:0)

不,你所拥有的将取代价值。您可以将它们作为字符串附加,或者将数字相加。但这是不好的做法;最好返回结果集,即:

SELECT
    (select count(*) FROM Master1 WHERE (...)) as 'Foo1',
    (SELECT count(*) FROM Master2 WHERE (...)) as 'Foo2',
    (select count(*) FROM Master3 WHERE (...)) as 'Foo3'

答案 1 :(得分:0)

怎么样:

IF EXISTS
(
SELECT 1 FROM Master1 WHERE (...)
UNION ALL
SELECT 1 FROM Master2 WHERE (...)
UNION ALL
SELECT 1 FROM Master3 WHERE (...)
)    
BEGIN
...
END

它应该做的伎俩,并迅速拉出来......

答案 2 :(得分:0)

如果这些都不存在,您只想运行。

您可以使用EXISTS关键字。

像这样。

IF NOT EXISTS SELECT ID FROM Master1 WHERE (...)
  IF NOT EXISTS SELECT ID FROM Master2 WHERE (...)
    IF NOT EXISTS SELECT ID FROM Master3 WHERE (...)
    BEGIN
      ..do stuff...
    END

注意我不使用count,如果count为零,则NOT EXISTS为真。选择任何列以使查询运行。

现在无法测试,语法可能如下所示:

IF NOT EXISTS (SELECT ID FROM Master1 WHERE (...))
  IF NOT EXISTS (SELECT ID FROM Master2 WHERE (...))
    IF NOT EXISTS (SELECT ID FROM Master3 WHERE (...))
    BEGIN
      ..do stuff...
    END