Is it possible to store part of a query as a variable to reuse?

Hello

I want to store a piece of code in a variable which I want to reuse it in other queries.

I am thinking of something like a text variable which however be read by SQL as a part of dynamic query/code instead of literal text.

Is that possible?

Thanks

Possible but useless. Use stored procedures. Read documentation for that

1 Like

Unfortunately I do not have access rights for stored procedures.

What is the purpose of creating this stub? Almost certainly there is a better way to accomplish the goal - without resorting to using dynamic SQL that will be used in multiple queries.

With that said - there is nothing stopping you from testing. Lookup sp_executesql - google about this and decide if that is the correct approach.

As long as you know all of the concerns/issues related to using dynamic SQL there isn't anything stopping you.

I have a set of criteria, e.g.
WHERE A=1
AND B=1

I want to reuse these criteria to other selections without having to rewrite them.

Obviously, these criteria cannot be stored as a text variable that will be read literally.

read documentation about views that might do what you want and reuse that view.

You should have privs to create stored procedures in a Development environment. If you're doing all this development work in a production environment, then you first need to have to get with the people in control and learn why that's such a very bad idea. Then, write a stored procedure and send it to the DBAs for review and, if they find nothing wrong with the code, they'll deploy it for you.

It can be what you'll call a "slow way of doing things" but it's necessary to protect the production environment. It will also keep you from having to do inefficient hacks like you're trying to do.