>-- * Step 1 - Create a table variable with identical structure of the actual table -- >DECLARE @Country TABLE (pk INT IDENTITY(1,1) PRIMARY KEY, newPK INT, CountryCode VARCHAR(60), > CountryName VARCHAR(60), isNew BIT DEFAULT(0)) > >DECLARE @recIndex INT >DECLARE @recCount INT >DECLARE @newRecPK INT >DECLARE @CountryCode CHAR(3) > >-- * Step 2 - Create INSERT for each default data -- >INSERT INTO @Country(CountryCode, CountryName) VALUES ('UK', 'United Kingdom') >INSERT INTO @Country(CountryCode, CountryName) VALUES ('JP', 'Japan') >INSERT INTO @Country(CountryCode, CountryName) VALUES ('CN', 'China') >INSERT INTO @Country(CountryCode, CountryName) VALUES ('HK', 'Hong Kong') > >-- * Step 3 - Compare Data -- >SET @recIndex = 1 >SET @recCount = (SELECT COUNT(*) FROM @Country) >SET @newRecPK = ISNULL((SELECT MAX(CountryPK) + 1 FROM Country),1) > >WHILE @recIndex <= @recCount > BEGIN > SET @CountryCode = (SELECT TOP 1 CountryCode FROM @Country WHERE pk = @recIndex) > > IF NOT EXISTS (SELECT * FROM Country WHERE CountryCode = @CountryCode) > BEGIN > UPDATE @Country SET newPK = @newRecPK, isNew = 1 WHERE pk = @recIndex > SET @newRecPK = @newRecPK + 1 > END > > SET @recIndex = @recIndex + 1 > END > >-- * Step 4 - Checking for State, City, Province ... -- >-- ... > >-- * Step 5 - Insert New Country, State, City, Province ... -- >INSERT INTO Country(CountryPK, CountryCode, CountryName) > SELECT newPK, CountryCode, CountryName FROM @Country WHERE isNew = 1 > >SELECT CAST(@@ROWCOUNT AS VARCHAR) + ' records added...' >>
>CREATE TABLE Country > (CountryPK INT PRIMARY KEY, CountryCode CHAR(3), CountryName VARCHAR(60)) >>