Yes, but conceptually it is something totally different. First of all, when you do:
SELECT * FROM Tabla WHERE Columna = @Valor
It is nothing more than a normal, parameterized query. The engine takes it, compiles it and can, if it so determines, make an execution plan that optimizes the query to minimize server resources and at the same time improve performance.
What you are looking for can be done without a doubt, but through something that is known as dynamic queries . In other words, judgments that you create dynamically. The simplest way, it could be something like this:
DECLARE @SQL NVARCHAR(MAX)
SELECT @SQL = 'SELECT *
FROM TABLA
WHERE COLUMNA_VARCHAR=''VALOR''
AND COLUMNA_NUMERICA=1'
EXEC(@SQL)
Observations:
- You can not combine a traditional sentence with a dynamic are different things
- the statements you write enclosed in quotes as you would normally write it but you must escape the internal quotes with double quotes
- This type of query can not be optimized by the engine, which we mentioned at the beginning
- If we want to parameterize the query, one way is to concatenate the values of each parameter by means of a variable, for example
.. COLUMNA_VARCHAR = ''' + @Valor + '''....'
, but NO is the appropriate form since this is susceptible to SQL Injection . The correct way is to use sp_execute_sql
and the parameterization of each parameter.