SQL Server 複製一條資料
阿新 • • 發佈:2020-12-10
原文:
https://bbs.csdn.net/topics/392362315
https://bbs.csdn.net/topics/391863876
insert into Table_1 (name) select name from Table_1 where id='1';select @@identity;
insert into Table_2 SELECT * from Table_1 where id='1'
/// <summary> /// typeName為類的字串形式,例子 : BLL.air_user -> "BLL.air_user" /// </summary> /// <param name="typeName"></param> /// <returns></returns> public Type typen(string typeName) { Type type = null; Assembly[] assemblyArray = AppDomain.CurrentDomain.GetAssemblies(); int assemblyArrayLength = assemblyArray.Length; for (int i = 0; i < assemblyArrayLength; ++i) { type = assemblyArray[i].GetType(typeName); if (type != null) { return type; } } for (int i = 0; (i < assemblyArrayLength); ++i) { Type[] typeArray = assemblyArray[i].GetTypes(); int typeArrayLength = typeArray.Length; for (int j = 0; j < typeArrayLength; ++j) { if (typeArray[j].Name.Equals(typeName)) { return typeArray[j]; } } } return type; }
using (var db = new CKQMSDB()) { if (true) { string strTableName = "AcountUser"; // 查詢資料 List<c1> list = db.Database.SqlQuery<c1>("select * from AcountUser").ToList(); // 修改資料 int result = db.Database.ExecuteSqlCommand($"update {strTableName} set name='123' where id='{list[0].id}'"); // 生成需要複製的列 string columnNames = ""; //Type t = typeof(c1); Type t = GetTypeByFullName("DAL.EF.AcountUser");// 獲取型別 t.GetProperties().ToList().ForEach(c=> { if (c.Name == "id") { return;// 去自增長id } columnNames += c.Name + ","; }); columnNames = columnNames.TrimEnd(','); // 複製行 返回新增資料的id //insert into Table_2 (name) select name from Table_1 where id='1' int autoId = db.Database.ExecuteSqlCommand($"insert into {strTableName} ({columnNames}) select {columnNames} from {strTableName} where id='1';select @@identity;"); string strSQL = "SELECT COUNT(*) FROM test"; int autoId2 = db.Database.SqlQuery<int>(strSQL).ToList()[0]; } }