0

My question is basic.

I am creating a stored procedure and have it the following variable:

@ConcatenarClausulaWhere

During the execution of the procedure, several conditions are concatenated in this variable to be inserted after the WHERE:

SELECT ID
FROM TABLE1
WHERE indStatus = 'True'
AND (Description LIKE '%' + @ STRING + '%')

My intention was to do something like:

SELECT ID
FROM TABLE1 The
WHERE indStatus = 'True'
AND (Description LIKE '%' + @ STRING + '%') + @ ConcatenarClausulaWhere

But, it is not possible. Why?

I am using SQL Server 2008

1 Answer 1

3

You need dynamic SQL to append a WHERE clause to a query. A SELECT statement is not just a string. You also need to be very wary of SQL injection here. How are you validating what users are entering into this where clause parameter?

DECLARE @sql NVARCHAR(MAX) = N'SELECT ID FROM dbo.TABLE1 
  WHERE indStatus = ''True'' AND (Description LIKE @String)'
  + @ConcatenarClausulaWhere;

EXEC sp_executesql @sql, N'@String NVARCHAR(MAX)', N'%' + @STRING + '%';
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.