[英]sql server usage IF NOT EXISTS in ASP.NET?
Is there is something wrong in my sql Query ? 我的sql查询有问题吗? I am having an error:
我有一个错误:
Incorrect syntax near the keyword 'join'.
关键字“ join”附近的语法不正确。
protected void Button1_Click1(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
if ((row.FindControl("CheckBox1") as CheckBox).Checked)
{
//string prNB = Session["prnb"].ToString();
SqlCommand cmd = new SqlCommand("insert into PrescTest(Test, idPresc)select @Test, idPresc from Prescription where prNB = @prNB and not exists(select test from PrescTest pt,join Prescription p on pt.idPresc = p.idPresc where prNB = @prNB)", conn);
cmd.Parameters.Add("Test", SqlDbType.NVarChar, 50).Value = row.Cells[2].Text;
cmd.Parameters.Add("prNB", SqlDbType.NVarChar, 50).Value = Session["prnb"].ToString();
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
Response.Redirect("PrescForm.aspx");
}
Sql tables diagram: sql表示意图:
There are several things wrong in your sql statement. sql语句中有几处错误。
insert...select
. insert...select
。 insert...select
statement insert...select
语句 begin
and end
keywords define a code block, much like {
and }
in c# - the open parenthesis right after the begin
keyword is a redundant (and I think also a syntax error). begin
和end
关键字定义一个代码块,类似于c#中的{
和}
begin
关键字之后的右括号是多余的(而且我认为这也是语法错误)。 same goes for the close parenthesis after the end
keyword end
关键字之后的右括号也是如此 A quick fix of your SQL statement is this: 您的SQL语句的快速修复方法是:
insert into PrescTest (Test,idPresc)
select @Test, idPresc
from Prescription
where prNB = @prNB
and not exists(
select test
from PrescTest pt
join Prescription p
on pt.idPresc = p.idPresc
where prNB = @prNB
)
Note that the not exists
have moved into the where clause so there really is no need for the if
. 请注意,
not exists
已移至where子句,因此实际上不需要if
。
Please note that this doesn't address the fact that you are running this sql for each row individually - you should look up table valued parameters to fix that issue. 请注意,这不能解决您正在逐行运行此sql的事实-您应该查找表值参数来解决该问题。
Here is your query. 这是您的查询。 It will work
会工作的
if not exists(select test from PrescTest pt, Prescription p where prNB ="+ prNB +"and pt.idPresc = p.idPresc) begin insert into PrescTest (Test,idPresc) values (@Test,(select idPresc from Prescription where prNB=" + prNB + "))end
在“结束”之前缺少两个右括号?
... + prNB + "))end))", conn);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.