我有一个insert命令,其值根据另一个表上的货币值计算。 Sql代码类似于
INSERT INTO table1 (column1,column2,column3,column4,column5,column6)
VALUES
(
value1 * (SELECT currency FROM currency_table WHERE date=date1),
value2 * (SELECT currency FROM currency_table WHERE date=date1),
value3 * (SELECT currency FROM currency_table WHERE date=date1),
value4 * (SELECT currency FROM currency_table WHERE date=date2),
value5 * (SELECT currency FROM currency_table WHERE date=date2),
value6 * (SELECT currency FROM currency_table WHERE date=date2),
)
UPDATE table1
SET column1 = value7 * (SELECT currency FROM currency_table WHERE date=date1),
column2 = value8 * (SELECT currency FROM currency_table WHERE date=date1),
column3 = value9 * (SELECT currency FROM currency_table WHERE date=date1),
column4 = value10 * (SELECT currency FROM currency_table WHERE date=date2),
column5 = value11 * (SELECT currency FROM currency_table WHERE date=date2),
column6 = value12 * (SELECT currency FROM currency_table WHERE date=date2)
WHERE column7 = value13
所以我得到货币价值3倍。考虑这是一个例子,因为我的实际查询有10次调用。
如何更改此查询以获取货币值不是3次,而只是1次。
考虑currency_table只有1行。
忘了提到这个查询是针对sql server 2008的
答案 0 :(得分:1)
尝试使用INSERT:
INSERT INTO table1 (column1,column2,column3)
VALUES
SELECT value1*currency, value2*currency, value3*currency
FROM currency_table;
答案 1 :(得分:1)
插入是Guneli提供的内容。 从语法上讲,查询不正确。 使用
INSERT INTO table1 (column1,column2,column3,column4,column5,column6)
SELECT value1*currency1, value2*currency1, value3*currency1,
value4*currency2, value5*currency2, value6*currency2
FROM (select (select currency from currency_table where date = @date1) currency1,
(select currency from currency_table where date = @date2) currency2) A;
要进行更新,您可以使用以下命令。
UPDATE t1
SET t1.column1 = value1 * c.currency1,
t1.column2 = value2 * c.currency1,
t1.column3 = value3 * c.currency1,
t1.Column4 = value4 * c.currency2,
t1.column5 = value5 * c.currency2,
t1.column6 = value6 * c.currency2
from table1 t1,
(select (select currency from currency_table where date = @date1) currency1,
(select currency from currency_table where date = @date2) currency2) C
WHERE t1.column4 = value4
它将与currency_table进行交叉连接,并假设currency_table具有单行,它将正确更新。
答案 2 :(得分:0)
加入怎么样?我不确定条件是你在没有任何where子句的情况下选择货币。
UPDATE table1 t1 INNER JOIN currency_table c ON [condition??]
SET t1.column1 = value1 * c.currency,
t1.column2 = value2 * c.currency,
t1.column3 = value3 * c.currency,
WHERE t1.column4 = value4