Home
Manage Your Code
Snippet: SQL Insert return Identity w/sample proc (C#)
Title: SQL Insert return Identity w/sample proc Language: C#
Description: accepts SqlParameter array, proc name and connection string name. Returns ID Views: 141
Author: David Ashworth Date Added: 10/3/2007
Copy Code  
1    public int ModifyDataReturnID(SqlParameter[] parameters, string ProcName, string ConnectionStringName)
2    {
3        SqlConnection cn;
4        SqlCommand cmd = new SqlCommand();
5        int returnID=0;
6
7        cn = new SqlConnection(ConfigurationManager.ConnectionStrings[ConnectionStringName].ToString());
8
9        try
10        {
11            cn.Open();
12            for (int i = 0; i < parameters.Length; i++)
13            {
14                SqlParameter sParam = (SqlParameter)parameters[i];
15                cmd.Parameters.Add(sParam);
16            }
17            SqlParameter paramIdOutput = new SqlParameter("@ProductID", SqlDbType.Int, 4);
18            paramIdOutput.Direction = ParameterDirection.Output;
19
20            cmd.Parameters.Add(paramIdOutput);
21
22            cmd.Connection = cn;
23            cmd.CommandType = CommandType.StoredProcedure;
24            cmd.CommandText = ProcName;
25            cmd.ExecuteNonQuery();
26            returnID = (int)cmd.Parameters["@ProductID"].Value;
27        }
28        catch (Exception ex)
29        {
30            throw ex;
31        }
32        finally
33        {
34            cn.Close();
35        }
36        return returnID;
37    }
38    /*
39     * ALTER PROCEDURE Blah
40(
41	@ProductTitle varchar(100),
42	@CategoryID int,
43	@OriginalPrice decimal
44)
45AS
46BEGIN
47	SET NOCOUNT ON;
48
49    INSERT Products(CategoryID, 
50					ProductName,
51					Price)
52	VALUES (@CategoryID,
53			@ProductTitle,
54			@OriginalPrice)
55
56	SELECT @ProductID = @@Identity
57END
58    */