我不知道代码的哪一部分是错误的。
这是我的存储过程
ALTER PROCEDURE dbo.AddNewNews
(@title nvarchar(50),
@text ntext,
@year int,
@month int,
@day int,
@id_writer int ,
@id_subject1 int,
@id_subject2 int,
@id_subject3 int,
@id_subject4 int,
@id_subject5 int)
AS
SET NOCOUNT ON
BEGIN TRANSACTION;
DECLARE @last_id_news int
BEGIN TRY
insert into news(title, text, year, month, day, id_writer)
values(@title, @text, @year, @month, @day, @id_writer)
set @last_id_news = SCOPE_IDENTITY()
if @id_subject1 is not null
begin
insert into news_subject (id_news,id_subject) values (@last_id_news,@id_subject1)
end
if @id_subject2 is not null
begin
insert into news_subject (id_news,id_subject) values (@last_id_news,@id_subject2)
end
if @id_subject3 is not null
begin
insert into news_subject (id_news,id_subject) values (@last_id_news,@id_subject3)
end
if @id_subject4 is not null
begin
insert into news_subject (id_news,id_subject) values (@last_id_news,@id_subject4)
end
if @id_subject5 is not null
begin
insert into news_subject (id_news,id_subject) values (@last_id_news,@id_subject5)
end
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION;
END CATCH;
RETURN
这就是我从C#代码中将参数发送到存储过程的方法:
public bool AddNewNews(News news, List<object> subject)
{
SqlParameter[] parameters = new SqlParameter[]
{
new SqlParameter ("@title", news.Id_news),
new SqlParameter ("@text", news.Text),
new SqlParameter ("@year", news.Year),
new SqlParameter ("@month", news.Month),
new SqlParameter ("@day", news.Day),
new SqlParameter ("@id_writer", news.Id_writer),
new SqlParameter ("@id_subject1", subject[0]),
new SqlParameter ("@id_subject2", subject[1]),
new SqlParameter ("@id_subject3", subject[2]),
new SqlParameter ("@id_subject4", subject[3]),
new SqlParameter ("@id_subject5", subject[4])
};
return SqlDBHelper.ExecuteNonQuery("AddNewNews", CommandType.StoredProcedure, parameters);
}
只是主题[i]可以为空
但我不知道它何时进入存储过程并检查id_subject
是否为false或其他部分代码?
答案 0 :(得分:3)
将参数更改为存储过程以具有默认值:
@id_subject1 int = null,
@id_subject2 int = null,
@id_subject3 int = null,
@id_subject4 int = null,
@id_subject5 int = null
答案 1 :(得分:1)
&#34;只是主题[i]可以为null,但我不知道它何时进入商店程序并检查id_subject是否为false或其他部分代码?&#34;
如果我理解正确,那么这些subject[i]
值可能是null
。传递值null
不起作用 - 该值不会被正确传递。
相反,请将参数发送到存储过程,如下所示:
new SqlParameter ("@id_subject3",subject[2] ?? DBNull.Value)