I am using stored procedures. In order to save time, I made some generic procedures that uses dynamic sqlin order to update. Such generic procedure is:
CREATE PROCEDURE [dbo].[SetField]
@company_id uniqueidentifier,
@id bigint,
@field_code nvarchar(50),
@value nvarchar(50)
AS
BEGIN
DECLARE @field_name nvarchar(50)
SET @field_name = NULL
SELECT @field_name=field_name
FROM dbo.FIELD_DEFINITION
WHERE field_code=@field_code
IF @field_name IS NOT NULL
BEGIN
IF @value IS NULL OR @value=''
BEGIN
SET @value='NULL'
END
ELSE
BEGIN
IF @field_code='START_DATE' OR @field_code='END_DATE'
BEGIN
SET @value = CONVERT(datetime, @value ,103)
END
SET @value=''''+@value+''''
END
DECLARE @sql nvarchar(1000)
SET @sql = 'UPDATE dbo.TABLE '+
'SET '+@field_name+'='+@value+' '+
'WHERE company_id=''' + CAST(@company_id as nvarchar(36)) + ''' AND '+
'id='+CAST(@id as nvarchar)
EXEC(@sql)
END
END
How can I prevent sql injection with this code?
You said:
In order to save time, I made some generic procedures that uses dynamic sql in order to update
If you'd asked first, we could have saved time and suggested this...
UPDATE
dbo.TABLE
SET
Field1 = CASE WHEN @field_name = 'Field1' THEN @value ELSE Field1 END,
Field2 = CASE WHEN @field_name = 'Field2' THEN @value ELSE Field2 END,
Field3 = CASE WHEN @field_name = 'Field3' THEN @value ELSE Field3 END,
...
Fieldn = CASE WHEN @field_name = 'Fieldn' THEN @value ELSE Fieldn END
WHERE
company_id = @company_id AND id = @id
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With