// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Data; using System.Data.SqlClient; namespace E { public class Program { public static void Main(string[] args) { using(SqlConnection con = new SqlConnection(@"Server=ARNEPC3\SQLEXPRESS;Integrated Security=SSPI;Database=Test")) { con.Open(); SqlCommand cre = new SqlCommand("CREATE TABLE autofun (id INTEGER IDENTITY PRIMARY KEY, txt VARCHAR(50))", con); cre.ExecuteNonQuery(); SqlCommand cresp = new SqlCommand("CREATE PROCEDURE usp_ins_auto @txt VARCHAR(50), @id INTEGER OUTPUT AS INSERT INTO autofun(txt) VALUES(@txt); SELECT @id = SCOPE_IDENTITY()", con); cresp.ExecuteNonQuery(); SqlCommand ins = new SqlCommand(); ins.CommandText = "usp_ins_auto"; ins.CommandType = CommandType.StoredProcedure; ins.Connection = con; SqlParameter p1 = new SqlParameter(); p1.ParameterName = "@txt"; p1.DbType = DbType.String; p1.Size = 50; p1.Direction = ParameterDirection.Input; ins.Parameters.Add(p1); SqlParameter p2 = new SqlParameter(); p2.ParameterName = "@id"; p2.DbType = DbType.Int32; p2.Direction = ParameterDirection.Output; ins.Parameters.Add(p2); for(int i = 0; i < 10; i++) { ins.Parameters["@txt"].Value = "Text #" + i; ins.ExecuteNonQuery(); int autoid = (int)p2.Value; Console.WriteLine(autoid); } SqlCommand drpsp = new SqlCommand("DROP PROCEDURE usp_ins_auto", con); drpsp.ExecuteNonQuery(); SqlCommand drp = new SqlCommand("DROP TABLE autofun", con); drp.ExecuteNonQuery(); } } } }