在存储过程中遇到一下的雷同语句,想写成函数调用
其中 @BasicUnit_1 为字段的值,BasicUnit_1为对应的字段名称
也就是说函数一个参数是字段名,一个参数是该字段的值if (@BasicUnit_1 != 0) and (@BasicUnit_1 != null)
begin
update ProductPrice set BasicUnit_1 = cast(FactoryPrice * @BasicUnit_1 as decimal(18,2)) where ProductID in 
(select ProductID from V_Products where @strWhere)
end if (@BasicUnit_2 != 0) and (@BasicUnit_2 != null)
begin
update ProductPrice set BasicUnit_2 = cast(FactoryPrice * @BasicUnit_2 as decimal(18,2)) where ProductID in 
(select ProductID from V_Products where @strWhere)
end

解决方案 »

  1.   

    NULL能用等号比较吗?你的结果正常吗?
      

  2.   

     @strWhere这类,不能用函数,只能用动态SQL方式执行.
    百度exec executesql
      

  3.   

    既然都是更新,那就不必用函数,用存储过程一样能解决,比如:
    CREATE PROC Test
    @ParaName VARCHAR(20),
    @ParaValue VARCHAR(20),
    @strWhere VARCHAR(100)
    AS 
    BEGIN
    DECLARE @Sql  VARCHAR(1000)

    IF ISNULL(@ParaValue,'0') !='0'
    BEGIN
    SET @Sql='UPDATE ProductPrice SET '+@ParaName+' = CAST(FactoryPrice * '+@ParaValue+' AS DECIMAL(18,2)) '+
                  'WHERE ProductID IN(SELECT ProductID FROM V_Products WHERE '+@strWhere+')'
         EXEC(@Sql)
    END
    END
      

  4.   

    鸟说得不错 表名或者字段名为变量的时候 请看看动态SQL基本语法。
      

  5.   

    if (@BasicUnit_1 != 0) and (@BasicUnit_1 != null)
    begin
    exec('update ProductPrice set BasicUnit_1 = cast(FactoryPrice *'+ ltrim(@BasicUnit_1)+' as decimal(18,2)) where ProductID in 
    (select ProductID from V_Products where '+@strWhere+'='+LTRIM(@BasicUnit_1)+')'
    end if (@BasicUnit_2 != 0) and (@BasicUnit_2 != null)
    begin
    exec('update ProductPrice set BasicUnit_1 = cast(FactoryPrice *'+ ltrim(@BasicUnit_2)+' as decimal(18,2)) where ProductID in 
    (select ProductID from V_Products where '+@strWhere+'='+LTRIM(@BasicUnit_2)+')'
    end这种情况要动态的哦