简体   繁体   中英

Return @@IDENTITY upon INSERT to use as variable

I have a function which I want to perform an INSERT or an UPDATE depending on whether the ProfileID found in the the imported .csv file is set to a current id or if it is a new one (if it's new, then it's marked as "New," "New1," "New2," etc. in the ProfileId column of the file).

Unfortunately, during the save process, there are a few functions that are called that require the use of the ProfileID . But if an INSERT is being performed, then the ProfileID is not known when these functions are called.

I have set up the INSERT query to return the ProfileID after inserting a new row using SCOPE_IDENTITY() , but I am not sure how to take this result and place it in a variable. Is there a way to do this?

This is the entire save function code:

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();
        }
    }
}

Use the ExecuteScalar() function this returns the scope identity or 0 when it has failed. Check the MSDN documentation and example.

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);
    }
}

Sarah, you should be able to add and use something of the like:

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

Just make sure you put the @ID parameter before the execute query command. You could even assign it to a variable as such:

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

Referenced idea is here .

UPDATE: I forgot to add that, as part of your insert statement, you need to do the following:

 SET @ID = SCOPE_IDENTITY();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM