简体   繁体   中英

Validate Data in SQL Server Table

I am trying to validate the data present in SQL Server table using a stored procedure. In one of the validation rules, i have to check whether the value of a particular column is present in another table.

Suppose i have a staging table with following columns Cat_ID, Amount, SRC_CDE

I have a 'maintable' with following columns CatID , Cat_Name

I have to validate whether the Cat_ID present in staging table exists in the 'maintable' for each row

I am using the following statement to validate

if((Select count(*) from maintable where CatID= @Cat_id) >0 )
-- Do something if data present

I want to know if there is any better way of doing the above thing other than using a select query for every row.

Can i use some sort of an array where i can fetch all the CatID from maintable and the check instead of using a select query.

Thanks

Using a left join to list all the invalid rows.

select
     staging.*
from
    staging
          left join maintable 
               on staging.catid=maintable.catid
where maintable.catid is null

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