如何比较两个表的列并根据SQL Server中存储过程的比较将值插入新表中

时间:2015-02-24 17:30:12

标签: sql sql-server sql-server-2008 stored-procedures

我想创建一个过程,该过程应检查两个表之间的列,并根据比较将值插入另一个表。

表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'。 如果您有任何疑问,请给我一些想法并告诉我。提前致谢。

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

听起来你想要这样的东西?

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