我打开SqlConnection
,然后使用foreach循环收集数据和存储过程。我使用Parameters.AddWithValue
将数据发送到我的存储过程中,但始终出现错误
System.Data.SqlClient.SqlException:'过程或函数spInsertLeafPickup指定了太多参数。
为什么?
存储过程:
CREATE TYPE Templeafpickup AS TABLE
(
ID INT PRIMARY KEY,
Address NVARCHAR(50),
SeasonType NVARCHAR(50),
NextPickupdate NVARCHAR(10)
)
CREATE PROCEDURE spInsertLeafPickup
@Templeafpickup Templeafpickup READONLY
AS
BEGIN
INSERT INTO LeafPickup([ID], [Address], [SeasonType], [NextPickupdate])
SELECT
[ID], [Address], [SeasonType], [NextPickupdate]
FROM
@Templeafpickup
END
C#类:
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con1 = new SqlConnection(cs))
{
con1.Open();
foreach (DataRow dr1 in dt.Rows)
{
SqlCommand cmd = new SqlCommand("spInsertLeafPickup", con1);
cmd.CommandType = CommandType.StoredProcedure;
//Insert stored procedure
cmd.Parameters.AddWithValue("@Address", dr1["PCOMBINED"]);
cmd.Parameters.AddWithValue("@SeasonType", dr1["PSSSTREET"]);
cmd.Parameters.AddWithValue("@NextPickupdate", dr1["ZST"]);
cmd.ExecuteNonQuery(); <= Error System.Data.SqlClient.SqlException: 'Procedure or function spInsertLeafPickup has too many arguments specified.'
}
con1.Close();
}
答案 0 :(得分:4)
您正在通过c#代码发送3个参数,但是仅在存储过程中声明了1个参数。请检查一下如何定义存储过程。 https://www.mssqltips.com/sqlservertutorial/160/sql-server-stored-procedure-tutorial/
create proc spInsertLeafPickup
@Address varchar,
@SeasonType int,
@NextPickupdate date
As
Begin
insert into LeafPickup([ID],[Address],[SeasonType],[NextPickupdate])
Values(NEWID(),@Address,@SeasonType,@NextPickupdate]
End
答案 1 :(得分:1)
如果LeafPickup的表定义的ID为INT和IDENTITY,则类似于:
Create Table dbo.LeafPickup
(
ID int IDENTITY(1,1) NOT NULL primary key,
Address nvarchar(50),
SeasonType nvarchar(50),
NextPickupdate nvarchar(10)
)
然后,您存储的proc将不会插入ID-它会自动为您生成。因此,存储的过程将是:
create proc dbo.spInsertLeafPickup
@Address nvarchar(50),
@SeasonType nvarchar(50),
@NextPickupdate nvarchar(10)
As
Begin
insert into LeafPickup(Address, SeasonType, NextPickupdate)
Values(@Address, @SeasonType, @NextPickupdate]
End