我已经开始在 Sql Server 2k8 中使用表值参数进行批处理操作。我非常喜欢这个功能,感觉它是在漫长的等待之后才出现的。
但是,为了从 .Net 代码中传递 TVP,构建 SQLMetaData[] 并在循环中填充值需要付出太多的努力。
如何避免在同步中维护 .Net 代码中的 Sql Server 和 SQLMetaData[] 对象中的用户定义类型?当我在 SQL 中更改类型定义时,没有简单的方法知道我在 .Net 的庞大代码中在哪里使用了该类型。
.Net Reflection 是否可以通过提供用户定义类型的名称来拯救程序员构造 SQLMetadata 并通过提供对象数组来帮助填充数据。
考虑这个例子:
SqlMetaData[] tvp_TradingAllocationRule = new SqlMetaData[13];
try
{
tvp_TradingAllocationRule[0] = new SqlMetaData("ID", SqlDbType.UniqueIdentifier);
tvp_TradingAllocationRule[1] = new SqlMetaData("Name", SqlDbType.VarChar, 255);
tvp_TradingAllocationRule[2] = new SqlMetaData("Description", SqlDbType.VarChar, -1);
tvp_TradingAllocationRule[3] = new SqlMetaData("Enabled", SqlDbType.Bit);
tvp_TradingAllocationRule[4] = new SqlMetaData("Category", SqlDbType.VarChar, 255);
tvp_TradingAllocationRule[5] = new SqlMetaData("Custom1", SqlDbType.VarChar, 255);
tvp_TradingAllocationRule[6] = new SqlMetaData("Custom2", SqlDbType.VarChar, 255);
tvp_TradingAllocationRule[7] = new SqlMetaData("Custom3", SqlDbType.VarChar, 255);
tvp_TradingAllocationRule[8] = new SqlMetaData("CreatedBy", SqlDbType.VarChar, 20);
tvp_TradingAllocationRule[9] = new SqlMetaData("CreatedTS", SqlDbType.DateTime);
tvp_TradingAllocationRule[10] = new SqlMetaData("ModifiedBy", SqlDbType.VarChar, 20);
tvp_TradingAllocationRule[11] = new SqlMetaData("ModifiedTS", SqlDbType.DateTime);
tvp_TradingAllocationRule[12] = new SqlMetaData("IsFactory", SqlDbType.Bit);
}
catch (Exception ex)
{
throw new Exception("Error Defining the tvp_TradingActionCondition in .Net" + ex.Message);
}
foreach (TradingRuleMetadata ruleMetadata in updatedRules)
{
SqlDataRecord tradingAllocationRule = new SqlDataRecord(tvp_TradingAllocationRule);
try
{
tradingAllocationRule.SetGuid(0, ruleMetadata.ID);
tradingAllocationRule.SetString(1, ruleMetadata.Name);
tradingAllocationRule.SetString(2, ruleMetadata.Description);
tradingAllocationRule.SetBoolean(3, ruleMetadata.Enabled);
tradingAllocationRule.SetString(4, ruleMetadata.Category);
tradingAllocationRule.SetString(5, ruleMetadata.Custom1);
tradingAllocationRule.SetString(6, ruleMetadata.Custom2);
tradingAllocationRule.SetString(7, ruleMetadata.Custom3);
tradingAllocationRule.SetString(8, ruleMetadata.CreatedBy);
tradingAllocationRule.SetDateTime(9, ruleMetadata.CreatedDate);
tradingAllocationRule.SetString(10, ruleMetadata.ModifiedBy);
tradingAllocationRule.SetDateTime(11, ruleMetadata.ModifiedDate);
tradingAllocationRule.SetBoolean(12, ruleMetadata.IsFactory);
tvp_TradingAllocationRuleRecords.Add(tradingAllocationRule);
}
catch (Exception ex)
{
}
}
现在,如果您的表有 100 列,想象一下您的代码。