如何在SQL Server中关联表并批量计算列乘积插入结果表
解决方案
先纠正初始SQL的问题,再给出完整的批量处理实现:
- 放弃旧式逗号关联表的写法,改用显式
INNER JOIN,可读性和执行效率更优 - 数值计算时
ISNULL的默认值要用数值0而非字符串'0',避免类型转换错误 - SQL本身是集合式操作,无需模拟C#循环,单条语句就能完成批量匹配、计算和插入
核心SQL代码
INSERT INTO results (string1, string2, tCost1, tCost2) SELECT t1.string1, t1.string2, ISNULL(t1.value1 * t2.price1, 0) AS tCost1, ISNULL(t1.value2 * t2.price2, 0) AS tCost2 FROM Table1 t1 INNER JOIN Table2 t2 ON t1.string1 = t2.string1 AND t1.string2 = t2.string2;
补充说明
INNER JOIN会只保留两个表中string1和string2完全匹配的行,符合你精准匹配的需求- 针对两组数值列(value1&price1、value2&price2)分别计算乘积,用
ISNULL处理任一值为NULL的情况,确保结果不会出现NULL - 这条语句会一次性处理所有64*1600规模的数据,直接将结果写入
results表,效率远高于在C#中读取Dataset后循环计算
如果需要保留Table1中所有行(即使Table2没有匹配项,对应tCost设为0),可以改用LEFT JOIN:
INSERT INTO results (string1, string2, tCost1, tCost2) SELECT t1.string1, t1.string2, ISNULL(t1.value1 * t2.price1, 0) AS tCost1, ISNULL(t1.value2 * t2.price2, 0) AS tCost2 FROM Table1 t1 LEFT JOIN Table2 t2 ON t1.string1 = t2.string1 AND t1.string2 = t2.string2;
内容的提问来源于stack exchange,提问作者user20537738
相关产品推荐
相关产品推荐

