问题描述
我正在使用Asp.net 2008和LINQ to SQL.
我有一个proc:
I am using Asp.net 2008 and LINQ to SQL.
I have aproc:
create proc sp_InsertProduct
@ID char(10),
@ProductName nvarchar(50)
as
if not exists(select * from PRODUCT where ID=@ID)
insert into PRODUCT values(@ID,@ProductName)
go
我已将所有proc拖入DataContext.dbml.
我创建了一个名为Connect的类:
I''ve drag all proc into DataContext.dbml.
I make a class named Connect:
public string InsertProduct(string ID, string ProductName)
{
//
DataContext dcon = new DataContext();
if (dcon.sp_InsertProduct(ID, ProductName) == 0)
{
return "fail";
}
else
{
return "success";
}
}
Default.aspx.cs:
Default.aspx.cs:
protected void btnInsert_Click(object sender, EventArgs e)
{
string msg=con.InsertProduct(txtID.Text.Trim(), txtProductName.Text.Trim());
Label1.Text = msg;
//re-load
//LoadData();
}
我输入:
ID ="P"
ProductName =页面"
有效.
我再次输入ID ="P"或ID ="Pn" ProductName ="Pen".我总是获得成功.
我尝试了(dcon.sp_InsertProduct(ID,ProductName)== 1)是否不变.
这是什么问题?
I enter:
ID = "P"
ProductName = "Pages"
It works.
I enter ID = "P" again or ID = "Pn" ProductName = "Pen".I always get success.
I tried if (dcon.sp_InsertProduct(ID, ProductName) == 1) but It does not change.
What is the problem?
推荐答案
if not exists(select * from PRODUCT where ID=@ID) -- This checks if the product ID is not already present in the table
如果您希望SP在ID已存在的情况下失败,则可以尝试通过 [ ^ ].
问候,
曼弗雷德(Manfred)
If you would want the SP to fail in case the ID was already present you could try throwing an exception via RAISERROR[^].
Regards,
Manfred
create proc sp_InsertProduct
@ID char(10),
@ProductName nvarchar(50)
as
BEGIN
if not exists(select * from PRODUCT where ID=@ID)
BEGIN
insert into PRODUCT values(@ID,@ProductName)
END
END
最好的问候
M.Mitwalli
Best Regards
M.Mitwalli
create proc sp_InsertProduct
@ID char(10),
@ProductName nvarchar(50)
as
begin
if not exists(select * from PRODUCT where ID=@ID)
begin
insert into PRODUCT(ID,ProductName) values(@ID,@ProductName)
end
End
go
这篇关于使用proc插入问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!