簡體   English   中英

如何比較兩個表的列並根據SQL Server中存儲過程的比較將值插入新表中

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

我想創建一個過程,該過程應檢查兩個表之間的列,並根據比較將值插入另一個表。

表格1:

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

表2:

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

表3:

create table table3
(
ID int,
ItemCheck char
)

表3的ID列的值應該與table1的ID列相同,如果table2表的ID列存在於table2中,則table3的值ItemCheck列應為'true'oterwise'false'。 如果您有任何疑問,請給我一些想法並告訴我。 提前致謝。

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

聽起來你想要這樣的東西?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM