1

I have a table which stores SQL queries. I am reading that and executing it by using EXECUTE sp_executesql. I was wondering that, if I want to modify this query, how can I do that?

If I have to add a variable in the end, I can do something like this:

DECLARE @sql1 NVARCHAR(MAX), @var NVARCHAR(20)

SET @sql1 = (SELECT Query FROM Table WHERE ID = 123)
SET @var = ' AND CONDITION2'

PRINT @sql1 + @var

Result:

UPDATE Table SET VALUE1 WHERE CONDITION1 AND CONDITION2

But if I want to add something in between, I'm not sure how to do that.

Query:

DECLARE @sql NVARCHAR(MAX)
SET @sql = (SELECT Query FROM Table WHERE ID = 123)
PRINT @sql

Actual result:

UPDATE Table SET VALUE1 WHERE CONDITION1

Expected:

UPDATE TOP (100) Table SET VALUE1 WHERE CONDITION1
1
  • Without some actual details nobody else knows how to do this either. Mostly because we have no idea what you are trying to do. You should start with table definitions and sample data. Then include what you are trying to do. Commented May 20, 2016 at 19:19

1 Answer 1

3

Just change your original query to include a placeholder

 SET @sql =  'UPDATE {0} Table SET VALUE1 WHERE CONDITION1';
 SET @top_condition = 'TOP(100)';
 SET @sql = REPLACE(@sql, 
                    '{0}', 
                    CONVERT(varchar(max), @top_condition)
                   );

You also can remove the top option if you want it

 SET @top_condition = '';
Sign up to request clarification or add additional context in comments.

1 Comment

This is exactly what I wanted.

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.