Check if data exist update else insert in SQL Server linked server - sql

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
;

Related

Data to be updated in database if it exists - else it should insert new records in SQL Server

I have created an insert statement to add data to DB if data not exists.
INSERT INTO SampleList(SampleId, Type, Description)
SELECT nr.SampleId, nr.Type, nr.Description
FROM (VALUES (1,'A','AA'),
(2,'B','BB'),
(3,'C','CC'),
(4,'D','DD')
) AS nr (SampleId,Type,Description)
LEFT JOIN SampleList cr ON cr.SampleId = nr.SampleId
WHERE cr.SampleId IS NULL
But I want to update the rows as well if data exists in the database.
Can you please help me to do so?
You can use MERGE :
MERGE SampleList cr
USING (SELECT nr.SampleId, nr.[Type], nr.[Description]
FROM (VALUES (1,'A','AA'), (2,'B','BB'), (3,'C','CC'), (4,'D','DD')
) as nr (SampleId, [Type], [Description])
) AS nr -- Use missed alias
ON (cr.SampleId = a.SampleId)
WHEN MATCHED THEN
UPDATE SET cr.[Type] = nr.[Type], cr.[Description] = nr.[Description]
WHEN NOT MATCHED BY TARGET THEN
INSERT (SampleId, [Type], [Description])
VALUES (nr.SampleId, nr.[Type], nr.[Description]); -- to terminate the merge
However, you can simplify your subquery with only values :
MERGE SampleList cr
USING ( VALUES (1,'A','AA'), (2,'B','BB'), (3,'C','CC'), (4,'D','DD')
) AS nr(SampleId, [Type], [Description])
ON (cr.SampleId = a.SampleId)
WHEN MATCHED THEN
UPDATE SET cr.[Type] = nr.[Type], cr.[Description] = nr.[Description]
WHEN NOT MATCHED BY TARGET THEN
INSERT (SampleId, [Type], [Description])
VALUES (nr.SampleId, nr.[Type], nr.[Description]); -- to terminate the merge

SQL Server : INSERT with a condition

I want to insert into my Files-Favorites table only if the values I'm trying to pass isn't in there already.
I tried:
INSERT INTO [Files-Favorites](fileID,auditorID)
VALUES ('1', '34')
WHERE (fileID != '1'
AND auditorID != '34')
This doesn't work. I'm trying not to INSERT duplicate values. How do I pull this off? This is for a Microsoft SQL Server 2005.
Thank you
Try using if not exists
IF NOT EXISTS(SELECT * FROM [Files-Favorites] WHERE fileID = '1' AND auditorID = '34')
BEGIN
INSERT INTO [Files-Favorites](fileID, auditorID)
VALUES('1', '34')
END
I would use a composite (multi-column) key rather than checking on each insert
ALTER TABLE [Files-Favorites] ADD CONSTRAINT unique_1 UNIQUE(fileID,auditorID)
We can use EXISTS with sub query to check the data existence and insert accordingly:
INSERT INTO [Files-Favorites](fileID,auditorID)
SELECT fileID, auditorID FROM (
SELECT '1' fileID,'34' auditorID) t
WHERE NOT EXISTS(SELECT tm.fileID FROM [Files-Favorites] tm
WHERE tm.fileID = t.fileID AND tm.auditorID = t.auditorID)

Insert into a Informix table or update if exists

I want to add a row to an Informix database table, but when a row exists with the same unique key I want to update the row.
I have found a solution for MySQL here which is as follows but I need it for Informix:
INSERT INTO table (id, name, age) VALUES(1, "A", 19) ON DUPLICATE KEY UPDATE name="A", age=19
You probably should use the MERGE statement.
Given a suitable table:
create table table (id serial not null primary key, name varchar(20) not null, age integer not null);
this SQL works:
MERGE INTO table AS dst
USING (SELECT 1 AS id, 'A' AS name, 19 AS age
FROM sysmaster:'informix'.sysdual
) AS src
ON dst.id = src.id
WHEN NOT MATCHED THEN INSERT (dst.id, dst.name, dst.age)
VALUES (src.id, src.name, src.age)
WHEN MATCHED THEN UPDATE SET dst.name = src.name, dst.age = src.age
Informix has interesting rules allowing the use of keywords as identifiers without needing double quotes (indeed, unless you have DELIMIDENT set in the environment, double quotes are simply an alternative to single quotes around strings).
You can try the same behavior using the MERGE statement:
Example, creation of the target table:
CREATE TABLE target
(
id SERIAL PRIMARY KEY CONSTRAINT pk_tst,
name CHAR(1),
age SMALLINT
);
Create a temporary source table and insert the record you want:
CREATE TEMP TABLE source
(
id INT,
name CHAR(1),
age SMALLINT
) WITH NO LOG;
INSERT INTO source (id, name, age) VALUES (1, 'A', 19);
The MERGE would be:
MERGE INTO target AS t
USING source AS s ON t.id = s.id
WHEN MATCHED THEN
UPDATE
SET t.name = s.name, t.age = s.age
WHEN NOT MATCHED THEN
INSERT (id, name, age)
VALUES (s.id, s.name, s.age);
You'll see that the record was inserted then you can:
UPDATE source
SET age = 20
WHERE id = 1;
And test the MERGE again.
Another way to do it is create a stored procedure, basically you will do the INSERT statement and check the SQL error code, if it's -100 you go for the UPDATE.
Something like:
CREATE PROCEDURE sp_insrt_target(v_id INT, v_name CHAR(1), v_age SMALLINT)
ON EXCEPTION IN (-100)
UPDATE target
SET name = v_name, age = v_age
WHERE id = v_id;
END EXCEPTION
INSERT INTO target VALUES (v_id, v_name, v_age);
END PROCEDURE;

Can I use "if not exists" to insert a row if the row is not already present in sql server?

insert into Attributes (Id, Disabled, AttributeValue)
values (#id, #disabled, #attr_value)
if not exists
(
select * from Attributes
where
Id = #id
)
Not sure, if this is a valid query.
I have seen people use where not exists. What is the difference and how to use where not exists? When I put where not exists, it is saying "Incorrect syntax near where."
I checked these question as well. But, it doesn't seem to have query to insert using if not exists.
Only inserting a row if it's not already there and
sql conditional insert if row doesn't already exist
Am I missing something? Should I only use where not exists?
Change it to INSERT INTO SELECT
INSERT INTO Attributes (Id, Disabled, AttributeValue)
SELECT #id, #disabled, #attr_value
WHERE NOT EXISTS
(
select * from Attributes
where
Id = #id
)
You would need to execute something like this
IF NOT EXISTS (select 1 from Attributes where Id = #id)
BEGIN
insert into Attributes (Id, Disabled, AttributeValue)
values (#id, #disabled, #attr_value)
END
This is typically done with an else clause to update the row if it exists.
Consider using MERGE:
MERGE INTO Attributes
USING ( values (#id, #disabled, #attr_value ) )
AS source ( Id, Disabled, AttributeValue )
ON source.Id = Attributes.Id
WHEN NOT MATCHED THEN
INSERT ( Id, Disabled, AttributeValue )
VALUES ( Id, Disabled, AttributeValue );
One advantage is that you can also update the values when the Id does exist e.g.
MERGE INTO Attributes
USING ( values (#id, #disabled, #attr_value ) )
AS source ( Id, Disabled, AttributeValue )
ON source.Id = Attributes.Id
WHEN MATCHED THEN
UPDATE
SET Id = source.Id,
Disabled = source.Disabled,
AttributeValue = source.AttributeValue
WHEN NOT MATCHED THEN
INSERT ( Id, Disabled, AttributeValue )
VALUES ( Id, Disabled, AttributeValue );

Get identity column values upon INSERT

I am using SQL Server 2008 to create a procedure.
I am using the following sql statement to insert into a audit table
insert into Listuser
(
UserID,
ListID,
AuditCreated
)
select
UserID,
ListID,
GETDATE()
from ListUser where Surname='surname'
I am using scope_identity() to get the identity column from the listuser table and insert the identity column to another logs table
If the select statement contains more than 1 value, how to get the identity value of both columns and insert into logs table?
Thanjs
If you need to capture multiple identity values being inserted, I'd use the OUTPUT clause:
DECLARE #TableOfIdentities TABLE (IdentValue INT)
INSERT INTO dbo.Listuser(UserID, ListID, AuditCreated)
OUTPUT Inserted.ID INTO #TableOfIdentities(IdentValue)
SELECT
UserID, ListID, GETDATE()
FROM
dbo.ListUser
WHERE
Surname = 'surname'
This will insert all rows into your ListUser table, and it will output all identities generated by this INSERT into the #TableOfIdentities table variable
Read more about the OUTPUT clause on MSDN
These values are inserted into the table variable, and you can select them out from that table variable after the insert, and do whatever you need to do with them:
SELECT * FROM #TableOfIdentities
Update: the use of the table variable here is just as an example - of course you can also output the data into a "normal" table in SQL Server - and you can also output multiple values for each inserted row, if you need that - so you can have something like:
INSERT INTO dbo.Listuser(UserID, ListID, AuditCreated)
OUTPUT Inserted.ID, Inserted.UserID, Inserted.SurName, GETDATE()
INTO AuditTable(IdentValue, UserID, Surname, InsertDate)
SELECT
UserID, ListID, GETDATE()
FROM
dbo.ListUser
WHERE
Surname = 'surname'