C# 存储过程插入或更新 DataTable 问题?
Posted
技术标签:
【中文标题】C# 存储过程插入或更新 DataTable 问题?【英文标题】:C# stored procedure insert or update with DataTable problem? 【发布时间】:2021-07-30 23:09:51 【问题描述】:我想用下面的代码添加或更新。我收到以下错误。我应该如何编辑这段代码?
必须声明标量变量“@UyeID”。 关键字“ELSE”附近的语法不正确。
我的代码:
CREATE TYPE [dbo].[BcgTarihiType] AS TABLE
(
[UyeID] int NOT NULL,
[BcgTarihi] [nvarchar](30) NULL
)
GO
CREATE PROCEDURE Insert_BcgTarihleri
(@tblBcgTarihleri BcgTarihiType READONLY)
AS
BEGIN
IF EXISTS (SELECT 1 FROM BcgTarihleri
WHERE UyeID = @UyeID AND BcgTarihi = @BcgTarihi)
BEGIN
UPDATE BcgTarihleri
SET UyeID = @UyeID, BcgTarihi = @BcgTarihi
WHERE UyeID = @UyeID
END
ELSE
BEGIN
INSERT INTO BcgTarihleri
VALUES (@UyeID, @BcgTarihi)
END
END
我也想这样问。下面的代码有效,但我只能添加。如果存在数据,如何更新?
CREATE TYPE [dbo].[BcgTarihiType] AS TABLE(
[UyeID] int NOT NULL,
[BcgTarihi] [nvarchar](30) NULL
)
GO
CREATE PROCEDURE Insert_BcgTarihleri
(
@tblBcgTarihleri BcgTarihiType READONLY
)
AS
BEGIN
INSERT into BcgTarihleri (UyeID,BcgTarihi)
SELECT UyeID, BcgTarihi FROM @tblBcgTarihleri;
END
【问题讨论】:
您没有在给定的代码中声明变量@UyeID
。也许您想将参数 @UyeID
带入您的过程 Insert_BcgTarihleri
?
这次我将它添加到代码中时出现此错误。 '过程或函数'Insert_BcgTarihleri'需要参数'@UyeID',但未提供。'
因为在调用Insert_BcgTarihleri
时,需要传递参数@UyeID
我将它作为数据表传递? cmd.Parameters.AddWithValue (@tblBcgTarihleri, 数据表);
向我们展示您的 C# 代码和don't use AddWithValue
。并且要更新,要么在 id 退出时添加更新,要么使用合并语句。
【参考方案1】:
@Boris Makhlin,@Dale K 感谢您的帮助,我用下面的代码解决了我的问题
CREATE TYPE [dbo].[BcgTarihiType] AS TABLE(
[UyeID] int NOT NULL,
[BcgTarihi] [nvarchar](30) NULL
)
GO
CREATE PROCEDURE [dbo].[Update_BcgTarihleri]
@tblBcgTarihleri BcgTarihiType READONLY
AS
BEGIN
SET NOCOUNT ON;
MERGE INTO BcgTarihleri b1
USING @tblBcgTarihleri b2
ON b1.UyeID = b2.UyeID AND b1.BcgTarihi = b2.BcgTarihi
WHEN MATCHED THEN
UPDATE SET b1.UyeID = b2.UyeID
,b1.BcgTarihi = b2.BcgTarihi
WHEN NOT MATCHED THEN
INSERT VALUES(b2.UyeID, b2.BcgTarihi);
END
【讨论】:
以上是关于C# 存储过程插入或更新 DataTable 问题?的主要内容,如果未能解决你的问题,请参考以下文章
SQL/C#:DataTable 到存储过程(从用户定义的表类型插入)- 转换错误
使用 DataTable 中的 OracleDataAdapter 更新记录并将记录插入 Oracle 表