简体   繁体   English

用于插入或更新数据库的SQL Server存储过程

[英]SQL Server Stored Procedure for Inserting or updating database

I am new to stored procedures and trying to learn things. 我是存储过程和尝试学习事物的新手。 I have a database table which looks likes this, 我有一个看起来像这样的数据库表,

 Acc   | Room |  ID | Name |  Email | Status |  Date  | Number 
=======+======+=====+======+========+========+========+========
(null) |  101 | 001 |  ABC | (null) |   EMP  | (null) | (null) 
(null) |  102 | 002 |  DEF | (null) |   TMP  | (null) | (null)   

I am creating a stored procedure to insert or update the data in the database depending on the ID. 我创建一个存储过程取决于ID数据库中插入或更新数据。 Not all the records has data to be inserted or updated. 并非所有记录都有要插入或更新的数据。

CREATE PROCEDURE [dbo].[uspInsertorUpdate]
    @room char(35),
    @id char(12),
    @name varchar(64),
    @status varchar(50),
AS
BEGIN
    SET NOCOUNT ON;
    IF EXISTS (SELECT null FROM emp WHERE ID = @id)
    BEGIN
       UPDATE emp 
       SET Room = @room, ID = @id, Name = @name, Status = @status
       WHERE ID = @id
    END

    INSERT INTO emp (Room, ID, Name, Status)
    VALUES(@room, @id, @name, @status);
END

Not sure if this is correct, will this create the other records with null. 不知道这是否正确,这会创建其他具有null的记录。

First check if the Id exist. 首先检查ID是否存在。 If it does not exist then its an insert else an update. 如果它不存在,则插入,否则更新。

The body of stored proc can be: 存储过程的主体可以是:

BEGIN

declare @v_count int

select @v_count = count(ID) from emp
where ID = @id

if (@v_count = 0)
insert into emp (Room, ID, Name, Status)
values (@room, @id, @name, @status)

else
update emp
set Room = @room, Name = @name, Status = @status
where ID = @id

END

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM