我有一个问题,我需要帮助,我知道问题所在,但我无法让它发挥作用。
SQL表列poci.Value的数据类型为nvarchar,我想要做的是计算在select语句中使用* 1.5获取的值。
poci.value的值是2.6,所以当我运行查询(见下文)时,我得到的结果是2.6。我只是想用* 1.5为结果添加一个计算,但这不会起作用,因为你不能像那样计算nvarchar ..
这是查询在没有尝试计算的情况下的显示方式:
SELECT poci.Value
FROM ProductionOrder po
LEFT JOIN Product p
ON p.ProductionOrderId = po.ProductionOrderId
LEFT JOIN ProductionOrderConfiguration poc
ON poc.ProductionOrderId = po.ProductionOrderId and poc.Valid = 1
LEFT JOIN ProductionOrderConfigurationItem poci
ON poci.ProductionOrderConfigurationId = poc.ProductionOrderConfigurationId
WHERE p.ProductId = #ProductId# and poci.Name = 'C_UE'
我尝试将此添加到查询的开头但不起作用:
DECLARE @Calc decimal(6,2) SET @Calc = 1.5 SELECT poci.value * @Calc AS test etc. etc..
请帮助我,我真的卡在这里!
指向tabledata的链接:
答案 0 :(得分:0)
试试这个:
SELECT CAST(poci.Value AS DECIMAL) * 1.5
等
或者:
CREATE TEMPORARY TABLE IF NOT EXISTS temp AS
SELECT poci.Value AS val
FROM [the rest of your original query];
SELECT CAST(val AS DECIMAL(6,2)) * 1.5 FROM temp;
答案 1 :(得分:0)
您可以尝试其中一种(MSSQL):
DECLARE @CALC AS DECIMAL(6,2);
SET @CALC=1.5;
WITH TEST_DATA AS (SELECT CAST('2.6' AS NVARCHAR) AS VALUE UNION ALL SELECT CAST('2.8' AS NVARCHAR) UNION ALL SELECT CAST('YES' AS NVARCHAR))
SELECT VALUE
, VALUE * @CALC AS NEW_VALUE
FROM TEST_DATA
WHERE ISNUMERIC(VALUE)>0
;
输出:
VALUE NEW_VALUE
------------------------------ ---------------------------------------
2.6 3.9000
2.8 4.2000
或者
DECLARE @CALC AS DECIMAL(6,2);
SET @CALC=1.5;
WITH TEST_DATA AS (SELECT CAST('2.6' AS NVARCHAR) AS VALUE UNION ALL SELECT CAST('2.8' AS NVARCHAR) UNION ALL SELECT CAST('YES' AS NVARCHAR))
SELECT VALUE
, CASE WHEN ISNUMERIC(VALUE)>0 THEN CAST( VALUE * @CALC AS NVARCHAR) ELSE VALUE END AS NEW_VALUE
FROM TEST_DATA
;
输出:
VALUE NEW_VALUE
------------------------------ ------------------------------
2.6 3.9000
2.8 4.2000
YES YES