我有两个学生桌(使用Microsoft SQL Server 2008 R2标准版)。我需要编写一个程序,这样如果第一个表有新学生,第二个表也会更新
这不起作用,我不知道为什么:
CREATE PROCEDURE [dbo].[CHECK_NEW]
AS
begin transaction
declare @tempId int
declare @tempName varchar
DECLARE c1 CURSOR FOR
SELECT kId, kName
FROM table1
OPEN c1
FETCH NEXT FROM c1
INTO @tempId, @tempName
WHILE @@FETCH_STATUS = 0
BEGIN
if (SELECT sId FROM table2) NOT IN(@tempId)
insert into table(sId, name) values(@tempId, @tempName)
END
commit
提前致谢
答案 0 :(得分:1)
试试这样....
CREATE PROCEDURE [dbo].[CHECK_NEW]
AS
Begin Try
begin transaction
Insert into Table2(ulid,Id,Name)
Select newid() as ulid, Id,name from ( Select Row_Number() over(Partition by a.id order by a.id) as row, a.Id,a.name from Table1 a where
not exists(Select * from Table2b where a.Id=b.Id)) t where row =1
Commit
End Try
Begin Catch
RollBack
End Catch