在INSERT上返回@@ IDENTITY以用作变量

时间:2014-08-13 19:43:55

标签: c# sql sql-server scope-identity

我有一个函数,我想执行INSERTUPDATE,具体取决于导入的ProfileID文件中找到的.csv是否设置为当前id或者如果它是新的(如果它是新的,那么它被标记为" New,"" New1,"" New2 ,"等文件的ProfileId列)。

不幸的是,在保存过程中,有一些被调用的函数需要使用ProfileID。但是如果正在执行INSERT,则在调用这些函数时不知道ProfileID

我已使用INSERT设置ProfileID查询以返回SCOPE_IDENTITY(),但我不确定如何将此结果放入变量中。有没有办法做到这一点?

这是整个保存功能代码:

private void SaveProfile(string[] curProfile)
{  
    string profId = GetValue(curProfile, (int)ProfileColumns.ProfileId).ToLower();

    string query ="";

    using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["AbleCommerce"].ToString()))
    {
        try
        {
            if (profId.Contains("new")) 
            {
                string insertQuery = "INSERT INTO ProductProfile (Name, Description, SpeciesLink, LineDraw, LineDrawThumbnail, ProfileThumbnail, ComponentThickness, ComponentWidth, FinishedThickness, FinishedWidth, ClassificationID, StockOrCust, ComponentFactor, Visibility, Notes, OrderBy) VALUES (@Name, @Description, @SpeciesLink, @LineDraw, @LineDrawThumbnail, @ProfileThumbnail, @ComponentThickness, @ComponentWidth, @FinishedThickness, @FinishedWidth, @ClassificationID, @StockOrCust, @ComponentFactor, @Visibility, @Notes, @OrderBy) SELECT SCOPE_IDENTITY()";
                Response.Write("PERFORM INSERT<br />");
                query = insertQuery;
            }

            {
                string updateQuery = "UPDATE ProductProfile SET Name = @Name, Description = @Description, SpeciesLink = @SpeciesLink, LineDraw = @LineDraw, LineDrawThumbnail = @LineDrawThumbnail, ProfileThumbnail = @ProfileThumbnail, ComponentThickness = @ComponentThickness, ComponentWidth = @ComponentWidth, FinishedThickness = @FinishedThickness, FinishedWidth = @FinishedWidth, ClassificationID = @ClassificationID, StockOrCust = @StockOrCust, ComponentFactor = @ComponentFactor, Visibility = @Visibility, Notes = @Notes, OrderBy = @OrderBy WHERE ProfileID = @profid";
                Response.Write("PERFORM UPDATE<br />");
                query = updateQuery;
            }

            SqlCommand cmd = new SqlCommand(query, cn);
            cmd.CommandType = CommandType.Text;

            cn.Open();

            cmd.Parameters.AddWithValue("@profid", GetValue(curProfile, (int)ProfileColumns.ProfileId).Trim());
            cmd.Parameters.AddWithValue("@Name", GetValue(curProfile, (int)ProfileColumns.Name).Trim());
            cmd.Parameters.AddWithValue("@Description", GetValue(curProfile, (int)ProfileColumns.Description).Trim());
            cmd.Parameters.AddWithValue("@SpeciesLink", GetValue(curProfile, (int)ProfileColumns.SpeciesLink).Trim());
            cmd.Parameters.AddWithValue("@Linedraw", GetValue(curProfile, (int)ProfileColumns.LineDraw).Trim());
            cmd.Parameters.AddWithValue("@LineDrawThumbnail", GetValue(curProfile, (int)ProfileColumns.LineDrawThumbnail).Trim());
            cmd.Parameters.AddWithValue("@ProfileThumbnail", GetValue(curProfile, (int)ProfileColumns.ProfileThumbnail).Trim());
            cmd.Parameters.AddWithValue("@ComponentThickness", GetValue(curProfile, (int)ProfileColumns.ComponentThickness).Trim());
            cmd.Parameters.AddWithValue("@ComponentWidth", GetValue(curProfile, (int)ProfileColumns.ComponentWidth).Trim());
            cmd.Parameters.AddWithValue("@FinishedThickness", GetValue(curProfile, (int)ProfileColumns.FinishedThickness).Trim());
            cmd.Parameters.AddWithValue("@FinishedWidth", GetValue(curProfile, (int)ProfileColumns.FinishedWidth).Trim());
            cmd.Parameters.AddWithValue("@ClassificationID", GetValue(curProfile, (int)ProfileColumns.ClassificationID).Trim());

            string stockCust = GetValue(curProfile, (int)ProfileColumns.StockOrCust).ToLower();

            switch (stockCust)
            {
                case "stock":
                    stockCust = "0";
                    break;
                case "custom":
                    stockCust = "1";
                    break;
                case "discontinued":
                    stockCust = "2";
                    break;
            }

            cmd.Parameters.AddWithValue("@StockOrCust", Convert.ToInt32(stockCust));
            cmd.Parameters.AddWithValue("@ComponentFactor", GetValue(curProfile, (int)ProfileColumns.ComponentFactor).Trim());

            string Visibility = GetValue(curProfile, (int)ProfileColumns.Visibility).ToLower();

            switch (Visibility)
            {
                case "public":
                    Visibility = "0";
                    break;
                case "private":
                    Visibility = "1";
                    break;
            }

            cmd.Parameters.AddWithValue("@Visibility", Convert.ToInt32(Visibility));
            cmd.Parameters.AddWithValue("@Notes", GetValue(curProfile, (int)ProfileColumns.Notes).Trim());
            cmd.Parameters.AddWithValue("@OrderBy", GetValue(curProfile, (int)ProfileColumns.OrderBy).Trim());

            cmd.ExecuteNonQuery();

            cn.Close();

            // this is the portion of the function that makes the call to other functions to complete the save process
            int profileID = Convert.ToInt32(GetValue(curProfile, (int)ProfileColumns.ProfileId));
            SaveArtchStyle(profileID, curProfile);
            SaveAssignedItems(profileID, curProfile);
            //update dimensions
            //UpdateProductDimensions(profileID, GetValue(curProfile, (int)ProfileColumns.FinishedThickness).Trim(), GetValue(curProfile, (int)ProfileColumns.FinishedWidth).Trim());
        }
        catch (Exception ex)
        {
            ErrorLabel.Text = "There was an error with the file." + ex.ToString();
        }
    }
}

2 个答案:

答案 0 :(得分:4)

使用ExecuteScalar()函数返回范围标识,或者在失败时返回0。查看MSDN文档和示例。

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar(v=vs.110).aspx

 Int32 newProdID = 0;
 string sql =
    "INSERT INTO Production.ProductCategory (Name) VALUES (@Name); "
    + "SELECT CAST(scope_identity() AS int)";
using (SqlConnection conn = new SqlConnection(connString))
{
    SqlCommand cmd = new SqlCommand(sql, conn);
    cmd.Parameters.Add("@Name", SqlDbType.VarChar);
    cmd.Parameters["@name"].Value = newName;
    try
    {
        conn.Open();
        newProdID = (Int32)cmd.ExecuteScalar();
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

答案 1 :(得分:2)

莎拉,你应该能够添加和使用类似的东西:

cmd.Parameters.Add("@ID", SqlDbType.Int, 4).Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
//Now just read the value of: cmd.Parameters["@ID"].value

确保在执行查询命令之前放置@ID参数。您甚至可以将其分配给变量:

var insertValue = cmd.Parameters["@ID"].value

参考的想法是here

更新:我忘记添加,作为插入语句的一部分,您需要执行以下操作:

 SET @ID = SCOPE_IDENTITY();