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
-- 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