// 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; class MainClass { public static bool IsInteger(string s) { try { int tmp = int.Parse(s); return true; } catch(FormatException) { return false; } } public static void Main(string[] args) { SqlConnection con1 = new SqlConnection("server=ARNEPC3;Integrated Security=SSPI;database=Test"); con1.Open(); SqlConnection con2 = new SqlConnection("server=ARNEPC3;Integrated Security=SSPI;database=Test"); con2.Open(); SqlCommand cre = new SqlCommand("CREATE TABLE MyTable (Id INTEGER, Adresse VARCHAR(25))", con1); cre.ExecuteNonQuery(); SqlCommand ins1 = new SqlCommand("INSERT INTO MyTable VALUES(1, 'a vej 11')", con1); ins1.ExecuteNonQuery(); SqlCommand ins2 = new SqlCommand("INSERT INTO MyTable VALUES(2, 'b vej 22')", con1); ins2.ExecuteNonQuery(); SqlCommand ins3 = new SqlCommand("INSERT INTO MyTable VALUES(3, 'c vej 33')", con1); ins3.ExecuteNonQuery(); SqlCommand ins4 = new SqlCommand("INSERT INTO MyTable VALUES(4, 'noget anderledes')", con1); ins4.ExecuteNonQuery(); SqlCommand alt = new SqlCommand("ALTER TABLE MyTable ADD Nummer INTEGER", con1); alt.ExecuteNonQuery(); SqlCommand sel1 = new SqlCommand("SELECT * FROM MyTable", con1); SqlDataReader rdr1 = sel1.ExecuteReader(); while(rdr1.Read()) { int id = (int)rdr1[0]; string gladresse = (string)rdr1[1]; int ix = gladresse.LastIndexOf(' '); string lastpart = gladresse.Substring(ix+1); if(IsInteger(lastpart)) { string nyadresse = gladresse.Substring(0, ix); int nummer = int.Parse(lastpart); SqlCommand upd = new SqlCommand("UPDATE MyTable SET Adresse = '" + nyadresse + "', nummer = " + nummer + " WHERE id = " + id, con2); upd.ExecuteNonQuery(); } } rdr1.Close(); SqlCommand sel2 = new SqlCommand("SELECT * FROM MyTable", con1); SqlDataReader rdr2 = sel2.ExecuteReader(); while(rdr2.Read()) { Console.WriteLine(rdr2[0] + "," + rdr2[1] + "," + rdr2[2]); } rdr2.Close(); SqlCommand drp = new SqlCommand("DROP TABLE MyTable", con1); drp.ExecuteNonQuery(); con1.Close(); con2.Close(); } }