Can anyone help with this case? How to use a dynamic query to insert into table?
DECLARE
@TypeCode varchar(25),
@BomDateB varchar(25),
@BomDateA varchar(25),
@TbName varchar(25),
@SQL varchar(max)
SET @TypeCode = 'PS-BPRG15AGW'
SET @TbName = 'z'+@TypeCode
SET @BomDateB = '8/19/2016'
SET @BomDateA = '8/20/2016'
SET @SQL = 'UPDATE [PMLite].[dbo].['+@TbName+']
SET [BOM Date] = '+@BomDateA+'
WHERE [BOM Date] = '+@BomDateB+''
EXEC sp_executesql @SQL
Your @
SQL
should beNVARCHAR
..So change like below
finally there will be some errors in your code ,to avoid conversion issues..so
change dates like
to
This would be the correct approach to do your update:
Like I've said in comments, do not concat your dynamic SQL when it's not absolutely needed (see
@BomDateA
and@BomDateB
parameters).And instead of wrapping your text with brackets, use
QUOTENAME()
. This built-in function is used to wrap your object names into brackets and secures your code from SQL Injection.Took from documentation: