如何比较两个 table 的列并根据 SQL 服务器中存储过程的比较将值插入新的 table
How to compare column of two table and insert a value into new table based on comparison in stored procedure in SQL Server
我想创建一个过程,它应该检查两个 table 之间的列,并根据比较将一个值插入另一个 table。
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
)
table 3 的 ID
列的值应与 table1 的 ID
列相同,并且
如果 table1 table 的 ID
列存在于 table2 中,那么 table3 的 ItemCheck
列的值应该是 'true' '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
我想创建一个过程,它应该检查两个 table 之间的列,并根据比较将一个值插入另一个 table。
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
)
table 3 的 ID
列的值应与 table1 的 ID
列相同,并且
如果 table1 table 的 ID
列存在于 table2 中,那么 table3 的 ItemCheck
列的值应该是 'true' '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