views:

24

answers:

3

Hi,

Is it possible to store different select value to the same variable?

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
A: 

No, what you've got there will replace the value. You can append them as strings though, or add up the numbers. But it's bad practice; better to return a resultset, i.e:

SELECT
    (select count(*) FROM Master1 WHERE (...)) as 'Foo1',
    (SELECT count(*) FROM Master2 WHERE (...)) as 'Foo2',
    (select count(*) FROM Master3 WHERE (...)) as 'Foo3'
Noon Silk
If any one of these statement returns 1 i have to stop the processPls. i want to know the better way
Geetha
Then declare individual variables and check the result after each assignment, *then* return the bunch as a result set, as per above. Is that clear?
Noon Silk
ok Thank You. No other better option?
Geetha
No, the only other way would be to append the items with some delimiter like ",", but this would be really bad practice. The best idea is to return the resultset.
Noon Silk
A: 

How about:

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

It should do the trick, and pull out quickly enough...

Rob Farley
A: 

You want to only run if none of these exist.

You could use the EXISTS keyword.

Something like this.

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

Note that I don't use count, if count is zero NOT EXISTS is true. Select any column to get the query to run.

Can't test right now, the syntax might look like this:

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
Hogan