【问题标题】:Dynamic query is not giving desired result动态查询没有给出想要的结果
【发布时间】:2017-08-15 16:27:30
【问题描述】:

我正在创建动态查询,如果它存在于表中,它正在更新列。当更新查询运行它给出错误。以下是过程

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 值 'Update Product set ProductSellingPrice = ((UnitPrice * [GSTRATE%]/100) + UnitPrice ) where ProductID = @id' 转换为数据类型 int 时转换失败。

请提前帮助和感谢

【问题讨论】:

  • 您发布的确切查询不会产生您所说的错误。

标签: sql sql-server tsql


【解决方案1】:

试试这个:

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

您不能使用 + 将 int 连接到字符串,因为 SQL Server 会尝试将字符串隐式转换为 int。
这就是为什么您需要将 int 显式转换为字符串的原因。

【讨论】:

  • @RamandeepSingh。 . .如果它解决了你的问题,你应该接受这个答案。
猜你喜欢
  • 2018-10-17
  • 2019-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-29
  • 1970-01-01
  • 1970-01-01
  • 2013-10-26
相关资源
最近更新 更多