2010-08-06 77 views
5

我無法理解錯誤,因爲我沒有試圖將數字變量@FQTROQ轉換爲數字。t-sql:將數據類型varchar轉換爲數字在語句中時出錯

declare @FQTROQ varchar(30) 
declare @FQNUTQ decimal(6,0) 
set @FQTROQ = 'R-354' 
set @FQNUTQ = 100 

SELECT (CASE WHEN (@FQTROQ is not null and @FQTROQ <> '') 
THEN (@FQTROQ) 
ELSE (@FQNUTQ) END) AS Numero_Troquel 

任何幫助?感謝

回答

4
declare @FQTROQ varchar(30) 
declare @FQNUTQ decimal(6,0) 
set @FQTROQ = 'R-354' 
set @FQNUTQ = 100 

SELECT CASE WHEN (@FQTROQ is not null and @FQTROQ <> '') 
THEN @FQTROQ 
ELSE CAST(@FQNUTQ AS VARCHAR(30)) END AS Numero_Troquel 

你需要轉換DECIMALVARCHAR使來自CASE語句的輸出具有相同的輸出值。

+0

我有一個類似的情況,我試圖根據列內容有條件地將列轉換爲十進制。我得到這個錯誤,直到我將我的十進制結果鑄造回varchar。非常感謝! – cBlaine 2013-08-16 11:52:44

0

你需要這樣做:

SELECT (CASE WHEN (@FQTROQ is not null and @FQTROQ <> '') 
THEN (@FQTROQ) 
ELSE (CAST(@FQNUTQ AS VARCHAR(30))) END) AS Numero_Troquel 

,因爲從一列返回的值需要匹配,SQL Server將嘗試將VARCHAR轉換爲數值,而不是其他方式,這是什麼你可能想要。

這是什麼命名約定,順便說一句?

+0

謝謝。我不知道! It Works – user354427 2010-08-06 10:41:50

0

這是因爲你有兩個不同類型的變量,即使你只是試圖返回其中的一個值爲「Numero_Troquel」,它們必須是兼容的類型。它所做的是試圖將@FQTROQ變量轉換爲DECIMAL。

你會要麼需要做的:

SELECT (CASE WHEN (@FQTROQ is not null and @FQTROQ <> '') 
THEN (@FQTROQ) 
ELSE (CAST(@FQNUTQ AS VARCHAR(30))) END) AS Numero_Troquel 

或者......

IF (@FQTROQ is not null and @FQTROQ <> '') 
    SELECT @FQTROQ AS Numero_Troquel -- this will return as a VARCHAR 
ELSE 
    SELECT @FQNUTQ AS Numero_Troquel -- this will return as a DECIMAL 
+0

非常感謝。簡單的答案我不知道 – user354427 2010-08-06 10:42:17

相關問題