简体   繁体   中英

If row exists then delete else Insert into a table using SQL Server stored procedures in SQL Server 2014

I have two tables Table1 and Table2 .

Now I want to write a stored procedure where if the record exists it will delete that record and if the record doesn't exists then it will insert the record.

NOTE: I don't have any primary key in the table. I may need to make a key based on multiple columns.

USE lan_db;  
GO  

CREATE PROCEDURE dbo.udm_to_app_invoice   
AS   
    SET NOCOUNT ON;  

    INSERT INTO dbo.dummy3
        SELECT 
            poc_name,
            poc_code,
            salesrep_code,
            invoice_date,
            product_name
        FROM
            [dbo].[src_nota_fiscal]
        WHERE
            LAST_UPDT = (SELECT MAX(last_updt) FROM DBO.SRC_NOTA_FISCAL); 
GO

Look into T-SQL IF...ELSE , that will probably be easiest.

IF Boolean_expression
{ sql_statement | statement_block }
[ ELSE
{ sql_statement | statement_block } ]

The boolean expression can be a subquery where you can use the EXISTS operator.

Specifies a subquery to test for the existence of rows.

To your question, the answer in pseudo SQL:

IF EXISTS(<SELECT statement that selects the record>) 
    <DELETE statement> 
ELSE 
    <INSERT statement>

An alternative would be to use the MERGE statement. However it is a cumbersome statement and IMO not that intuitive.

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