I’m using static SQL for 99% of the time, but a recent scenario led me to write a dynamic SQL and I want to make sure I didn’t miss anything before this SQL is released to production.
The tables’ names are a combination of a prefix, a 2 letters variable and a suffix and column name is a prefix + 2 letters variable.
First I’ve checked that @p_param is 2 letters length and is “whitelisted”:
IF (LEN(@p_param) = 2 and (@p_param = ‘aa’ or @p_param = ‘bb’ or @p_param = ‘cc’ or @p_param = ‘dd’ or @p_param = ‘aa’)
BEGIN
set @p_table_name = 'table_' + @p_param + '_suffix';
set @sql = 'update ' + QUOTENAME(@p_table_name) + ' set column_name = 2 where id in (1,2,3,4);';
EXEC sp_executesql @sql;
--Here I’m checking the second parameter that I will create the column name with
IF (LEN(@p_column) = 2 and (@p_column = 'ce' or @p_column = 'pt')
BEGIN
Set @column_name = 'column_name_' + @p_column_param;
set @second_sql = 'update ' + QUOTENAME(@p_table_name) + ' set ' +
QUOTENAME(@column_name) + ' = 2 where id in (@p_some_param);';
EXEC sp_executesql @second_sql, N'@p_some_param NVARCHAR(200)', @p_some_param = @p_some_param;
END
END
Is this use case safe? Are there any pitfalls I should be a ware of?
@p_some_paramis a list, that query won't work the way you expect it to.