简体   繁体   中英

How to add New values into a table from a different table in SQL Server?

I have recently migrated from Access backend to SQL Server. I have my front end in MS Access and backend in SQL Server. Now whenever a new client is created by the user, a stored procedure runs automatically which actually splits the data from the main table into different tables eg: The client table would have all the data and then it would be split into different tables like Address, Phone, etc. Now every time the store procedure runs all the values from the client's table is inserted into other tables as all the value is duplicated. I just want the new values to be inserted into different tables and not the old values which are already present there.

[Stored Procedure]

INSERT INTO [dbo].[ClientRelationstbl]
           ([CNR](FK)
           ,[RelationTypeID]
           ,[FirstName]
           ,[Surname]
           ,[LastUpdated]
           ,[UpdatedBy]
           ,[Active])
     Select
            [CNR](PK)
           ,1
           ,[FNM]
           ,[SNM]
           ,GETDATE()
           ,124
           ,1
    FROM [dbo].[clientstbl]
    Where [FNM] is not null or [SNM] is not null AND [CNR] NOT IN (SELECT DISTINCT [CNR] FROM [ClientRelationstbl])

[FNM] = FirstName Mother [SNM] = Surname Mother

Now, whenever I try to run this it stores duplicate values in the table. I just want to store the new values in the ClientRelation table.

Please use "NOT EXISTS" instead of "NOT IN":

INSERT INTO [dbo].[clientrelationstbl]
            ([Cnr](fk),
             [relationtypeid],
             [firstname],
             [surname],
             [lastupdated],
             [updatedby],
             [active])
SELECT a.[Cnr](pk),
       1,
       a.[fnm],
       a.[snm],
       Getdate(),
       124,
       1
FROM   [dbo].[clientstbl] a
WHERE  (a.[fnm] IS NOT NULL OR a.[snm] IS NOT NULL)
       AND NOT EXISTS (SELECT b.[cnr]
                             FROM [clientrelationstbl] b 
                             WHERE b.[Cnr] = a.[Cnr]) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM