CREATE PROCEDURE [dbo].[SCD1] AS
-- SLOWLY CHANGING DIMENSION'S 1 (SCD1)
-- DROP PROCEDURE SCD1
-- EXEC SCD1
SET NOCOUNT ON
BEGIN
--INSERT OF NEW SOURCE VALUES INTO TEMP TABLE
SELECT SRC.* INTO #TEMP
FROM SRC_CUST SRC
LEFT OUTER JOIN DIM_CUST TGT ON SRC.CUSTOMERID = TGT.CUSTOMERID
WHERE TGT.CUSTOMERID IS NULL
--INSERT RECORDS THAT NEEDS TO BE UPDATED INTO #TEMP1 TABLE
SELECT SRC.* INTO #TEMP1
FROM SRC_CUST SRC
INNER JOIN DIM_CUST TGT ON SRC.CUSTOMERID = TGT.CUSTOMERID
WHERE (TGT.COMPANYNAME <> SRC.COMPANYNAME
OR TGT.CONTACTNAME <> SRC.CONTACTNAME
OR TGT.CONTACTTITLE <> SRC.CONTACTTITLE
OR TGT.ADDRESS <> SRC.ADDRESS
OR ISNULL(TGT.CITY,'UNK') <> SRC.CITY
OR TGT.REGION <> SRC.REGION
OR TGT.POSTALCODE <> SRC.POSTALCODE
OR TGT.COUNTRY <> SRC.COUNTRY
OR TGT.PHONE <> SRC.PHONE
OR TGT.FAX <> SRC.FAX)
--CHECK FOR THE EXISTENCE OF VALUES IN THE #TEMP TABLE
IF EXISTS(SELECT COUNT(1) FROM #TEMP)
BEGIN
--INSERT NEW RECORDS INTO THE TARGET TABLE
INSERT INTO DIM_CUST
SELECT SRC.* FROM #TEMP SRC
DROP TABLE #TEMP
PRINT 'NEW RECORDS INSERTED'
END
ELSE
DROP TABLE #TEMP
PRINT 'NO NEW RECORDS TO INSERT';
IF EXISTS(SELECT COUNT(1) FROM #TEMP1)
BEGIN
--CHECK FOR THE EXISTENCE OF VALUES IN THE #TEMP1 TABLE
-- UPDATES THE RECORDS INTO THE TARGET TABLE
UPDATE TGT
SET TGT.COMPANYNAME = SRC.COMPANYNAME
,TGT.CONTACTNAME = SRC.CONTACTNAME
,TGT.CONTACTTITLE = SRC.CONTACTTITLE
,TGT.ADDRESS = SRC.ADDRESS
,TGT.CITY = SRC.CITY
,TGT.REGION = SRC.REGION
,TGT.POSTALCODE = SRC.POSTALCODE
,TGT.COUNTRY = SRC.COUNTRY
,TGT.PHONE = SRC.PHONE
,TGT.FAX = SRC.FAX
FROM DIM_CUST TGT
INNER JOIN #TEMP1 SRC ON TGT.CUSTOMERID = SRC.CUSTOMERID
DROP TABLE #TEMP1
PRINT 'UPDATED RECORDS'
END
ELSE
DROP TABLE #TEMP1
PRINT 'NO RECORDS THERE TO UPDATE'
END
执行此存储过程时遇到的问题是,即使if条件满足,它也会进入else部分。任何人都可以帮我调试这个存储过程。
我所采用的源表是Northwind数据库中的Customer
表。
感谢。
答案 0 :(得分:2)
有2个问题
你也需要BEGIN / END ELSE子句。只有DROP在ELSE中被激活:PRINT *总是“使它像你报告的那样运行
...
ELSE
BEGIN
DROP TABLE #TEMP
PRINT 'NO NEW RECORDS TO INSERT';
END
...
ELSE
BEGIN
DROP TABLE #TEMP1
PRINT 'NO RECORDS THERE TO UPDATE'
END
其次,这些都是真的
IF EXISTS(SELECT COUNT(1) FROM #TEMP)
...
IF EXISTS(SELECT COUNT(1) FROM #TEMP1)
你需要的只是。
IF EXISTS(SELECT * FROM #TEMP)
请参阅我的这些答案来解释原因: