我有一个实体 Report
我想将其值插入到数据库表中。 Report
的以下属性必须插入:
reportID - int
RoleID - int
Created_BY = SYSTEM(default)
CURRENT_TIMESTAMP
现在问题出在第二个属性上。我有一份关于 LIST<ROLES>
的报告属性。 ROLES
是一个定义明确的实体,它有一个 ID
和一个 NAME
.从这个列表中,我必须提取每个角色并将每个角色的 ID 插入到表中。
所以我的查询目前如下所示:
INSERT INTO REPORT_MARJORIE_ROLE(REPORT_ID, ROLE_ID, CREATED_BY, CREATED)
VALUES({0}, {1}, 'SYSTEM', CURRENT_TIMESTAMP)
我解析这些值的 C# 代码如下:
try
{
StringBuilder _objSQL = new StringBuilder();
_objSQL.AppendFormat(Queries.Report.ReportQueries.ADD_NEW_ROLES, report.ID, "report.MarjorieRoles.Add(MarjorieRole"));
_objDBWriteConnection.ExecuteQuery(_objSQL.ToString());
_objDBWriteConnection.Commit();
_IsRolesAdded = true;
}
所以请指导我如何从 C# 函数添加角色
最佳答案
我假设您说的是 SQL(结构化查询语言),而您实际上是指 Microsoft SQL Server(实际的数据库产品)- 对吗?
您不能将整个列表作为一个整体插入到 SQL Server 中 - 您需要为每个条目插入一行。这意味着,您需要多次调用 INSERT 语句。
这样做:
// define the INSERT statement using **PARAMETERS**
string insertStmt = "INSERT INTO dbo.REPORT_MARJORIE_ROLE(REPORT_ID, ROLE_ID, CREATED_BY, CREATED) " +
"VALUES(@ReportID, @RoleID, 'SYSTEM', CURRENT_TIMESTAMP)";
// set up connection and command objects in ADO.NET
using(SqlConnection conn = new SqlConnection(-your-connection-string-here))
using(SqlCommand cmd = new SqlCommand(insertStmt, conn)
{
// define parameters - ReportID is the same for each execution, so set value here
cmd.Parameters.Add("@ReportID", SqlDbType.Int).Value = YourReportID;
cmd.Parameters.Add("@RoleID", SqlDbType.Int);
conn.Open();
// iterate over all RoleID's and execute the INSERT statement for each of them
foreach(int roleID in ListOfRoleIDs)
{
cmd.Parameters["@RoleID"].Value = roleID;
cmd.ExecuteNonQuery();
}
conn.Close();
}
关于c# - 插入列表 <> 到 SQL Server 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10680910/