Use sp_executesql to deal with the Image type Parameter in SP

What I want is to realise this StoreProcedure. When execute the SP, if the parameter is not null then update the correspond fields or else keep it as original value. Everybody knows that I should use dynamic SQL. I agree with it. However, here is the problem. If the field type is Char we can set up a SQL sentence like this
SET @sql = @sql + ' Phone = ''' + @phone  + ''''

But what if the field type is Image, we can't write it in the same way.
SET @sql = ' set IMAGE = ' + @image
it will raise an error tell you that the @image parameter is not char type. That's true. How can we deal with it?
I look up many resource and get this down.
Use sp_executesql. It is a build-in SP in SQL Server. This SP support parameters replacement. For more detail, please get it from MSDN. I will show an example as follows

 

ALTER   PROCEDURE   [ dbo ] . [ UpdateSP ]  
    
--  Add the parameters for the stored procedure here
@myName   NVARCHAR ( 50 ),
@image   IMAGE ,
@phone   NVARCHAR ( 50 )
AS
BEGIN
DECLARE   @sql   NVARCHAR ( MAX )
DECLARE   @imgParameter   NVARCHAR ( 50 )
    
--  SET NOCOUNT ON added to prevent extra result sets from
     --  interfering with SELECT statements.
     SET  NOCOUNT  ON ;
    
SET   @sql   =   '' ;
    
    
    
IF   @image   is   not   NULL
    
BEGIN
        
SET   @sql   =   '  set IMAGE = @image '   
    
END
    
    
SET   @imgParameter   =  N ' @image IMAGE '

    
IF   @phone   IS   NOT   NULL
    
BEGIN
        
IF   @sql   <>   ''
            
SET   @sql   =   @sql   +   '  ,  '
        
ELSE
            
SET   @sql   =   @sql   +   '  SET  '
        
SET   @sql   =   @sql   +   '  Phone =  '''   +   @phone    +   ''''
    
END
    
    
    
if   @sql   <>   ''
    
BEGIN
        
SET   @sql   =   ' UPDATE MyTbl  '   +   @sql   +   '  WHERE MyName =  '''   +   @myName   +   ''''
        
Exec  sp_executesql  @sql , @imgParameter , @image
    
END
    
ELSE
    
BEGIN
        
PRINT   ' EMPTY '
    
END
END

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值