简体   繁体   中英

How to compare column of two table and insert a value into new table based on comparison in stored procedure in SQL Server

I want to create a procedure which should check a column between two tables and insert a value into another table based on comparison.

Table 1:

create table table1
(
ID int not null primary key,
)

Table 2:

Create table table2
(
ItemID int not null primary key,
ID int FOREIGN KEY REFERENCES Orders(OrderID) ,
Descp Text
)

Table 3:

create table table3
(
ID int,
ItemCheck char
)

value of ID column of table 3 should be same as table1's ID column and if ID column of table1 table exist in table2 then value ItemCheck column of table3 should be 'true' oterwise 'false'. Please give me some ideas and let me know if you have any doubt. Thanks in advance.

Declare @col1 varchar(10)
Declare @col2 varchar(10)

SET @col1 = Select column1 from table1 where id =1
SET @col1 = Select column1 from table1 where id =2

IF(@col1 == @col2)
BEGIN 
  //  insert statement goes here
END

Sounds like you want something like this?

TRUNCATE table3;
INSERT INTO table3 (ID, ItemCheck)
  SELECT ID, 
         CASE WHEN EXISTS (SELECT 1 FROM table2 t2 WHERE ID = t.ID)
              THEN 'T' 
              ELSE 'F' 
         END
    FROM table1 t

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