简体   繁体   中英

Verify existence of two columns in different tables in a single SQL transaction

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

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
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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM