[英]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.我最近从 Access 后端迁移到 SQL 服务器。 I have my front end in MS Access and backend in SQL Server.
我的前端在 MS Access 中,后端在 SQL 服务器中。 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 [FNM] = 名字母亲 [SNM] = 姓母亲
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.
我只想将新值存储在 ClientRelation 表中。
Please use "NOT EXISTS" instead of "NOT IN":请使用“NOT EXISTS”而不是“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])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.