0

I'm trying to verify if data exists in two different tables in a single transaction. The reason for the single transaction is the database gets hit about 1-3 million times a day so adding anymore than 1 extra transaction would increase that number up to 9 million, and my poor little server needs a break :)

So I need to check if an ID exists in table X and table Y and return the results to my VB.net script so I can handle the outcome Ideally something like this would work

if exists (select id from X where id = @id)
print 'True,' else print 'False,'
if exists (select id from Y where id = @id)
print 'True' else print 'False'

Which gives me "True, True" if exists in both or "True, False" etc etc... But that only displays in SQL print and not actually returning it as an object/string or array values that I can use.

I'm open to any sort of solution of this nature that can give me two results from a single transaction and how to handle that response in vb. Thanks

4

3 回答 3

2
SELECT
    Case When EXISTS(SELECT 1 FROM X WHERE id = @id) Then 1 Else 0 End AS IsInX,
    Case When EXISTS(SELECT 1 FROM Y WHERE id = @id) Then 1 Else 0 End AS IsInY
于 2012-05-31T14:00:39.847 回答
1
select (select COUNT(*) from X where id = @id) AS x_exists,
       (select COUNT(*) from Y where id = @id) AS y_exists

This returns one data row with two fields, each containing either 0 or 1 (or more, if id is not unique).

于 2012-05-31T13:56:37.657 回答
0
CREATE PROCEDURE CheckIDOnTables(@ID int)
AS
BEGIN
DECLARE @X AS NVARCHAR(10)
DECLARE @Y AS NVARCHAR(10)
Set @X = 'False'
Set @Y = 'False'
if exists (select id from TableX where id = @ID) 
    Set @X = 'True'
if exists (select id from TableY where id = @ID) 
    Set @Y = 'True'
SELECT @X AS XExists, @Y AS YEsists
END

It will give you your desired results.

于 2012-05-31T14:07:27.750 回答