SQL Parameterization can be achieved through different techniques depending on the programmatic context, from a pure SQL point of view, we simply need to declare the values as variables, then we can use those variables within your normal SQL commands.
DECLARE @firstName VARCHAR(50) = 'Geoff';
DECLARE @lastName VARCHAR(50) = 'Bridges';
DECLARE @recordId INT = 5;
INSERT INTO [dbo].[Names]
([First_Name]
,[Last_Name])
VALUES (@firstName, @lastName)
Updating the same record, when the ID
is known to be 5
:
UPDATE [dbo].[Names] SET
Last_Name = @lastName,
First_Name = @firstName
WHERE ID = @recordId
In most cases the declaration section is managed from your application logic, and not usually expressed explicitly in SQL.
UPDATE
After reading through the extended comments, its clear we need more information here. If you are constructing dynamic SQL scripts from your application logic, using declared parameters not going to provide much safety on its own, you will still need to sanitize the input if you wish to guard against SQL Injection attacks.
Most higher languages like C# will have a built in mechanism to sanitize and validate SQL parameter input, yes, ultimately this results at some level with the parameters being serialised into strings and injected into a SQL script, these mechanisms will prevent your script from executing if the type and or length validation fails.
The following is an example of an injection attack that will break even if you use parameterised syntax where you are only substituting the values:
User sets their first name as: hello'; DROP TABLE Names;SELECT '
Now, inject that into your script:
DECLARE @firstName VARCHAR(50) = 'hello'; DROP TABLE Names; SELECT '';
...
Whilst that may not result in the table being dropped, it is obvious that all sorts of commands could be executed in this way. I don't want to give you any specific malicious ideas, but it's common for attackers to grant permissions to external users or to otherwise exploit access to the underlying system, perhaps even to execute custom scripts directly from the command line.
- this is one reason why you should NEVER use SA logins!
However, if the application were to sanitize the input data first, either through a framework, 3rd party library or manually, it should have escaped the name value and executed something like this instead:
DECLARE @firstName VARCHAR(50) = 'hello''; DROP TABLE Names; SELECT''';
...
Which would be a silly name for a user, but at least the table wasn't dropped.
Alternatively, if your request is to specifically use the VALUES
Table Constructor syntax for the update, then that is possible too, though not advised...
UPDATE [dbo].[Names] SET
Last_Name = lName,
First_Name = fName
FROM [dbo].[Names]
INNER JOIN
(VALUES (@firstName, @lastName, @recordId)) as V(fName, lName, recId) ON V.recId = Names.ID