2017-08-15 86 views
0

我正在創建更新列的動態查詢,如果它存在於表中。當更新查詢正在運行時,它發生錯誤。以下是該過程動態查詢沒有給出想要的結果

Create Procedure spr_UpdateColumnWithTotalPrice 
@id int 
as 
begin 

if not exists 
(
    Select * from INFORMATION_SCHEMA.COLUMNS 
    where TABLE_NAME = 'Product' 
    and 
    COLUMN_NAME = 'ProductSellingPrice' 
) 
Begin 
    Declare @SellingPrice varchar(max) 


    Set @SellingPrice = 'Alter table Product add ProductSellingPrice int' 
    Exec(@SellingPrice) 

    Print 'Table altered' 
End 
Else 
Begin 
     Set @SellingPrice = 'Update Product set ProductSellingPrice = ((UnitPrice * [GSTRATE%]/100) + UnitPrice) where ProductID = @id' 
     Exec(@SellingPrice) 
     Print 'Table updated' 
End 

我得到以下結果: - 轉換爲varchar值「更新產品時設置

轉換失敗ProductSellingPrice =((單價* [GSTRATE%]/100)+ UnitPrice)其中ProductID = @id'爲數據類型int。

請在此先感謝幫助和

+0

您發佈的確切查詢不會產生您所說的錯誤。 –

回答

2

試試這個:

Set @SellingPrice = 'Update Product set ProductSellingPrice = ((UnitPrice * [GSTRATE%]/100) + UnitPrice) where ProductID = '+ CAST(@id as varchar(13)) 

不能使用+連接int一個字符串,因爲SQL Server將嘗試隱式轉換字符串轉換爲int。
這就是爲什麼你需要顯式地將int轉換爲字符串。

+0

它的工作原理和感謝指導 –

+0

[很高興幫助: - )](http://meta.stackoverflow.com/questions/291325/how-to-show-appreciation-to-a-user-on-stackoverflow/291327 #291327) –

+0

@RamandeepSingh。 。 。如果它解決了你的問題,你應該接受這個答案。 –