如何使用用户定义的表类型向 SQL Server 表中插入数据,并检查重复数据?

huangapple go评论66阅读模式
英文:

How to insert data in sql server table using user defined table types, and check duplicate data?

问题

我正在使用C#将Excel文件数据上传到SQL Server。我正在创建一个数据表并将其传递给存储过程。我已经创建了如下的存储过程。

创建过程 [dbo].[usp_InsertData]
@dt AS dbo.tbl_employees READONLY,
@CREATEDBY as varchar(50),
@folderPath as nvarchar(3000),
@result as varchar(100) OUTPUT

AS

BEGIN

INSERT INTO Employees(Name, Email, Branch, CreatedBy, FolderPath)
SELECT Name, Email, Branch, @CREATEDBY, @folderPath
FROM @dt;

set @result='Success';

select @result
Print @result

END

但它没有给我输出值。我还想验证用户定义表(dbo.tbl_employees)中的重复数据与实际表(Employees)中的重复数据。如果有重复数据,应该显示消息“重复数据”。不知道如何做。有人能帮我让它工作吗?谢谢

英文:

I am using C# to upload excel file data in sql server. I am creating a datatable and passing it to SP. I've created SP like below

    Create PROCEDURE [dbo].[usp_InsertData]

  @dt AS dbo.tbl_employees READONLY,
  @CREATEDBY as varchar(50),
  @folderPath as nvarchar(3000),
  @result as varchar(100) OUTPUT

AS
BEGIN
 

 INSERT INTO Employees(Name, Email, Branch, CreatedBy, FolderPath)
  SELECT Name, Email, Branch,@CREATEDBY, @folderPath
  FROM @dt;	
set @result='Success';


select @result
Print @result
END	

But it's not giving me output value. Also I want to validate duplicate data from user-defined-table(dbo.tbl_employees) with actual table (Employees). If there are any duplicate data then it should give a message 'Duplicate data'. Don't know how to do it. Can someone help me to make it work?
Thanks

答案1

得分: 1

你应该在表上设置一个唯一约束,以确保不会出现重复数据。

但如果你想要一个特殊的返回值(而不只是抛出错误),你需要先检查你的数据,然后有条件地返回一个值。

英文:

You should have a unique constraint on your table to ensure you don't get duplicate data.

But if you want a special return value (rather than just throwing an error), you need to check your data first, and conditionally return a value.

CREATE OR ALTER PROCEDURE dbo.usp_InsertData
  @dt AS dbo.tbl_employees READONLY,
  @CREATEDBY as varchar(50),
  @folderPath as nvarchar(3000),
  @result as varchar(100) OUTPUT
AS

SET XACT_ABORT ON;

BEGIN TRAN;

IF EXISTS (SELECT 1
    FROM Employees e WITH (HOLDLOCK)
    JOIN @dt dt ON dt.Name = e.Name
)
BEGIN
    SET @result = 'Duplicate data';
    ROLLBACK;
    RETURN;
END;

INSERT INTO Employees
    (Name, Email, Branch, CreatedBy, FolderPath)
SELECT Name, Email, Branch, @CREATEDBY, @folderPath
FROM @dt;

SET @result = 'Success';

COMMIT;

If you are having problems getting information out of an OUTPUT parameter in C# then that is a separate question. There are already many posts that show you how to do that.

huangapple
  • 本文由 发表于 2023年4月11日 16:08:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/75983716.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定