简体   繁体   English

强制存储过程在将数据插入表中之前进行检查

[英]Forcing Stored Procedure to check before inserting data into table

I created this Stored Procedure, 我创建了此存储过程,

Now what I want to do is, to always replace if a similiar type of record exists within table, 现在我要做的是,如果表中存在类似的记录类型,则要始终替换,

here's the sp, 这是sp,

USE [DBName]
GO

CREATE procedure [dbo].[InsertDD]
(
    @ColumnA varchar(1000), 
    @ColumnB varchar(1000),
    @CurrentDateAndTime datetime

)
AS

INSERT Into TableName
(
    ColumnA,    
    ColumnB,
    CurrentDateAndTime
)
Values
(
    @ColumnA,   
    @ColumnB,
    @CurrentDateAndTime
)

Now If table already has Column B value (regardless of difference in letters eg capital or lower case) then just update CurrentDateAndTime value. 现在,如果表已经具有Column B值(不管字母大小写或小写字母之间的差异),则只需更新CurrentDateAndTime值即可。

If not then simply add three of the values. 如果没有,则只需添加三个值。

Do the update, and if it didn't find any record to update, do the insert: 进行更新,如果找不到任何要更新的记录,请执行插入操作:

update TableName 
set CurrentDateAndTime = @CurrentDateAndTime
where ColumnB = @ColumnB

if (@@rowcount = 0) begin

  insert into TableName (
    ColumnA,    
    ColumnB,
    CurrentDateAndTime
  ) values (
    @ColumnA,   
    @ColumnB,
    @CurrentDateAndTime
  )

end

Have a search for the IF ... EXISTS command. 搜索IF ... EXISTS命令。 Ultimatily you can also use the MERGE statement, which determines using a SELECT if a row already exists and you can do a UPDATE. 最后,您还可以使用MERGE语句,该语句使用SELECT确定是否已存在行,并且可以执行UPDATE。

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

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