使用主键将数据插入SQL表.对于伪造-允许插入错误或首先选择? [英] Inserting data into SQL Table with Primary Key. For dupes - allow insert error or Select first?

查看:67
本文介绍了使用主键将数据插入SQL表.对于伪造-允许插入错误或首先选择?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个表格,例如:

CREATE TABLE dbo.MyTestData (testdata varchar(50) NOT NULL) 

ALTER TABLE dbo.MyTestData WITH NOCHECK ADD CONSTRAINT [PK_MyTestData] PRIMARY KEY  CLUSTERED (testdata) 

考虑到我们想要一个唯一的'testdata'列表,当我们完成收集要从已知重复项的外部数据列表中添加的项目时...执行插入存储过程时,应将该过程编写为测试存在还是应该允许错误?最常见的做法是什么?我一直对存在进行测试,但昨晚正在辩论……

And given that we want a unique list of 'testdata' when we are done gathering items to be added from a list of external data with known duplicates... When performing an insert stored procedure should the procedure be written to test for existence or should it just allow for error? What's the most common practice? I've always performed the test for existence but was debating this last night...

CREATE PROCEDURE dbo.dmsInsertTestData @ptestdata VarChar(50)
AS
  SET NOCOUNT ON

  IF NOT EXISTS(SELECT testdata FROM dbo.MyTestData WHERE testdata=@ptestdata)
  BEGIN
    INSERT INTO dbo.MyTestData (testdata ) VALUES (@ptestdata)
  END

RETURN 0

还是在执行此命令时捕获/忽略PK违反错误?

or just capture/ignore PK violation errors when executing this one?

CREATE PROCEDURE dbo.dmsInsertTestData @ptestdata VarChar(50)
AS
  SET NOCOUNT ON
  INSERT INTO dbo.MyTestData (testdata ) VALUES (@ptestdata)
RETURN 0

推荐答案

我总是在一条语句中这样做:

I always do it in one statement:

INSERT INTO dbo.MyTestData (testdata ) VALUES (@ptestdata)
WHERE NOT EXISTS(SELECT 1 FROM dbo.MyTestData WHERE testdata=@ptestdata)

这篇关于使用主键将数据插入SQL表.对于伪造-允许插入错误或首先选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆