我是存储过程的新手,如果有人可以帮我,我有一个请求。
我有两个具有以下列的相同模式temp_20130426
和temp_20130427
的表:
PID SID Relationship LName FName Col1 PII LastUpdated
每天 LastUpdated
列都会更改,
我的要求是编写一个SP来比较除LastUpdate
之外的每一列的两个表数据,然后将数据写入新的
PID SID Relationship LName FName Col1 PII LastUpdated Delete
Delete
列必须在第二天没有记录时标记
感谢您的帮助!!
答案 0 :(得分:0)
我认为这就是你所需要的 -
declare @temp_20130427 table (
PID INT
,SID INT
,Relationship char(1)
,Lname varchar(50)
,Fname varchar(50)
,Col1 varchar(50)
,PII varchar(50)
,LastUpdated datetime
)
insert into @temp_20130427 values (1,1,'P','Khan','Shahrukh','Actor','Famous',GETDATE())
,(2,2,'P','Khan','Salman','Actor','Famous',GETDATE())
,(3,3,'P','Khan','Saif Ali','Actor','Famous',GETDATE())
select * from @temp_20130427
declare @temp_20130426 table (
PID INT
,SID INT
,Relationship char(1)
,Lname varchar(50)
,Fname varchar(50)
,Col1 varchar(50)
,PII varchar(50)
,LastUpdated datetime
,[Delete] bit
)
insert into @temp_20130426 values (1,1,'P','Khan','Shahrukh','Actor','Famous',GETDATE(),NULL)
,(2,2,'P','Khan','Salman','Actor','Famous',GETDATE(),NULL)
,(3,3,'P','Khan','Saif Ali','Actor','Famous',GETDATE(),NULL)
,(4,4,'P','Kumar','Akshay','Actor','Famous',GETDATE(),NULL)
select * from @temp_20130426
--Insert the compared data in a new #tmp table
IF OBJECT_ID ('tempdb..#tmp') is not null
DROP TABLE #tmp
select PID
,SID
,Relationship
,Lname
,Fname
,Col1
,PII
INTO #tmp
from @temp_20130426
EXCEPT
select PID
,SID
,Relationship
,Lname
,Fname
,Col1
,PII
from @temp_20130427
IF OBJECT_ID('TEMPDB..#NEW_TABLE') IS NOT NULL
DROP TABLE #NEW_TABLE
select told.PID
,told.SID
,told.Relationship
,told.Lname
,told.Fname
,told.Col1
,told.PII
,told.LastUpdated
INTO #NEW_TABLE
from #tmp t
join @temp_20130426 tOld
on tOld.PID = t.PID
--See the different data set in #NEW_TABLE table
SELECT * FROM #NEW_TABLE
--Flag Delete column where record does not exist in next day table
update t
set t.[Delete] = 1
from @temp_20130426 t
where PID not in (select PID from @temp_20130427)
--See the updated flagged data
select * from @temp_20130426
答案 1 :(得分:0)
Nullable列需要包装在ISNULL中以进行连接比较,但是这应该可以让您每天丢失所有记录。
select oldt.*,1
from temp_20130426 oldt
left join temp_20130427 newt ON
oldt.[PID]=newt.[PID]
AND oldt.[SID]=newt.[SID]
AND oldt.[Relationship]=newt.[Relationship]
AND oldt.[LName]=newt.[LName]
AND oldt.[FName]=newt.[FName]
AND oldt.[Col1]=newt.[Col1]
AND oldt.[PII]=newt.[PII]
WHERE newt.[PID] IS NULL