Possible Duplicate:
Solutions for INSERT OR UPDATE on SQL Server
I am in a great trouble that I want write a SQL query that include a conditional statement.
EG : I have a SQL table with columns ID,NAME,STATUS so before I insert value in to this table I want to check the name that is already exists in the table. If it is exist then I want to update the status value.
Is it possible to write the query by using queryString (SQL Server query instead of stored procedure) method, If anybody knw pls help me. I am using SQL Server 2008 R2
You want the MERGE query syntax
From the documentation ( http://technet.microsoft.com/en-us/library/bb510625.aspx )
MERGE Production.UnitMeasure AS target
USING (SELECT @UnitMeasureCode, @Name) AS source (UnitMeasureCode, Name)
ON (target.UnitMeasureCode = source.UnitMeasureCode)
WHEN MATCHED THEN
UPDATE SET Name = source.Name
WHEN NOT MATCHED THEN
INSERT (UnitMeasureCode, Name)
VALUES (source.UnitMeasureCode, source.Name)
OUTPUT deleted.*, $action, inserted.* INTO #MyTempTable
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With