我需要知道SQl查询,如果记录不存在或者记录存在更新记录,如何将新记录插入sql server。
以下我试过的
string sql= "if record not exists (select * from OpCircular Where circular_No='" + tbcicularno.Text.Trim() + "') INSERT INTO OpCircular(circular_No, fromDate, toDate, empId) VALUES ('" + tbcicularno.Text.Trim() + "','" +from+ "','" + to + "','Testing') If not Exists Update Set fromDate='" +from+ "'"
答案 0 :(得分:0)
if exists(select 1 from table where id = 4)
begin
(do what u want)
end
else
begin
(do what u want)
end
答案 1 :(得分:0)
请尝试以下代码:
IF EXISTS(SELECT TOP(1) Id FROM Article WHERE CategoryId = 3)
BEGIN
-- Update Script
END
ELSE
BEGIN
-- Insert Script
END;
答案 2 :(得分:0)
首先,您应该在插入新记录并执行所需操作时检查表中的所有记录。
您可以执行以下操作:
声明计数器变量并用0
初始化它 declare @icnt int = 0
现在检查表中的记录并将计数存储在变量中:
set @icnt = select count(*) from 'YourTableName' where (here you need to check all the fields with "and" condition)
现在如果列存在,那么@icnt
值将变为1,否则它将保持为0.所以,设置if..else条件就像这样。
if(@icnt > 0)
begin
(Put your update query here)
end
else
(Put your insert query here)
end
更多信息,您也可以执行this document
答案 3 :(得分:0)
我强烈建议使用存储过程,因为它有很多好处,并且可以防止SQL注入攻击。下面是一个示例SP,如果给定的ID不存在,则会在表中插入记录并返回IDENTITY,或者只是更新它:
CREATE PROCEDURE [dbo].[usp_product_insert_update]
-- Add the parameters for the stored procedure here
@id int=NULL,
@description nvarchar(50)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
UPDATE Product
SET Description=@description
WHERE Id=@id
IF (@@ROWCOUNT=0)
INSERT INTO Product (Description)
OUTPUT Inserted.ID
VALUES (@description)
END
在SQL Management Studio上 此调用将插入一条记录并返回ID = 1
usp_product_insert_update null,'Demo'
此调用将更新ID = 1
的记录usp_product_insert_update 1,'Demo2'
答案 4 :(得分:0)
自2008年以来,您可以为sql-server尝试Merge:
MERGE INTO OpCircular WITH (HOLDLOCK) AS target
USING
(SELECT :circular_No as circular_No) as source
ON
(target.circular_No = source.circular_No)
WHEN MATCHED THEN UPDATE SET fromDate = :fromDate
WHEN NOT MATCHED THEN INSERT (circular_No, fromDate, toDate, empId)
VALUES (:circular_No, :fromDate, :toDate, 'Testing');
注意:所有[:标识符]只是外部数据的占位符