I try to insert data from table in another. I want to check all rows, if row exists, just update, if row does not exist, insert it (based on ID
).
I have this insert
statement:
insert into d1.dbo.UrlRecord (EntityId, EntityName, Slug, IsActive, LanguageId)
select
Id, 'Category',
REPLACE(Name, ' ', '-'), 1, 0
from d2.dbo.Category
if Id
exist just update with new value else insert
I want to make it run dynamically using job in SQL Server
Try the following MERGE script
MERGE d1.dbo.UrlRecord TT
USING
(
SELECT
Id,'Category' as EntityName,REPLACE(Name,' ','-') as Slug,1 as IsActive,0 as LanguageID
FROM d2.dbo.Category
)ST on TT.EntityId = ST.id
WHEN NOT MATCHED THEN
INSERT ( EntityId,EntityName,Slug,IsActive,LanguageId)
VALUES (ST.Id,ST.EntityName,ST.Slug, ST.IsActive,ST.LanguageID)
WHEN MATCHED THEN
UPDATE
SET
TT.EntityName = ST.EntityName,
TT.Slug = ST.Slug,
TT.IsActive = ST.IsActive,
TT.LanguageId=ST.LanguageID
;
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.