然后两个ExecuteScalar查询

时间:2014-08-05 15:12:35

标签: c# sql sql-server

我正在寻找一种方法来检查Customer表中是否存在客户ID,以及是否存在于要查询的表中。

如果它在Customer表中不存在,或者它已经存在于被查询的表中(或者它在Customer中,但也已存在于相关表中),那么我不希望它插入数据。 / p>

我想也许我可以做if ifif代码 - 更多代码 - if..if代码 - 否则,但这不起作用。这就是我的意思:

cmd.CommandText = "SELECT COUNT(*) FROM Customer WHERE customer_id = @cid";
    cmd.Connection = conn;

    conn.Open();
    int count = (int)cmd.ExecuteScalar();
    conn.Close();

    if (count < 1)
    {
        System.Web.HttpContext.Current.Response.Write("<script>alert('Customer ID does not exist and will not be submitted')</script>");
        tb0.Focus();
    }

    cmd.CommandText = "SELECT COUNT(*) FROM table_name WHERE customer_id = @cid";
    cmd.Connection = conn;

    conn.Open();
    int count2 = (int)cmd.ExecuteScalar();
    conn.Close();
    if(count2 > 0)
    {
        System.Web.HttpContext.Current.Response.Write("<script>alert('Customer ID already exists in table_name and will not be submitted')</script>");
        tb0.Focus();
    }


    else
    {
        cmd.CommandText = "INSERT INTO table_name VALUES(@cid, @val1, @val2, @val3, @val4, @val5)";
        cmd.Connection = conn;

        conn.Open();
        cmd.ExecuteNonQuery();
        conn.Close(); }

除非我发表评论,否则第二个会起作用,我认为第一个会被忽略?我不是很确定,但如果对方被注释掉,他们都会工作

回答错误:

关键字'THEN'附近的语法不正确。 关键字“ELSE”附近的语法不正确。 关键字'THEN'附近的语法不正确。 关键字“ELSE”附近的语法不正确。

@"IF NOT EXISTS (SELECT * FROM Customer WHERE customer_id = @cid) THEN BEGIN
    SELECT 'NO_CUSTOMER' as Result 
END ELSE IF EXISTS (SELECT * FROM table_name WHERE customer_id = @cid) THEN BEGIN
    SELECT 'ALREADY_RECORD' as Result
END ELSE BEGIN
    INSERT INTO table_name VALUES(@cid, @val1, @val2, @val3, @val4, @val5);
    SELECT 'SUCCESS' AS Result;
END";

1 个答案:

答案 0 :(得分:2)

为什么不尝试更简单的东西,比如这个?

    cmd = conn.CreateCommand();
cmd.CommandText =
  @"IF NOT EXISTS (SELECT * FROM Customer WHERE customer_id = @cid) THEN BEGIN
        SELECT 'NO_CUSTOMER' as Result 
    END ELSE IF EXISTS (SELECT * FROM table_name WHERE customer_id = @cid) THEN BEGIN
        SELECT 'ALREADY_RECORD' as Result
    END ELSE BEGIN
        INSERT INTO table_name VALUES(@cid, @val1, @val2, @val3, @val4, @val5);
        SELECT 'SUCCESS' AS Result;
    END";

cmd.Parameters.AddWithValue(@cid, ...);        
cmd.Parameters.AddWithValue(@val1, ...);
cmd.Parameters.AddWithValue(@val2, ...);
...
switch((string)cmd.ExecuteScalar()) {
    case "NO_CUSTOMER":
        System.Web.HttpContext.Current.Response.Write("<script>alert('Customer ID does not exist and will not be submitted')</script>");
    tb0.Focus();
        break;
        case "ALREADY_RECORD":
        System.Web.HttpContext.Current.Response.Write("<script>alert('Customer ID already exists in table_name and will not be submitted')</script>");
    tb0.Focus();
        break;
}