I know I can get the results I want by using a Dynamic SQL string but wondered if I could utilise SQLCMD for some of my more complex queries.
I have a situation where I'm running a query on one database that obtains some of its data from a separate database. So far so straightforward!
However, this separate database changes name each year(in this example db_2016). So I have a query like this (but longer and more complex!)
Mycte1 as (
select x,y,z from main_database.dbo.table
),
Mycte2 as (
select db_2016.dbo.field1,db_2016.dbo.field2 from
db_2016.dbo.another_table
)
Now with SQLCMD I can add
:isvar SourceDatabase db_2016
and the select now becomes
Mycte1 as (
select x,y,z from main_database.dbo.table
),
Mycte2 as (
select $(SourceDatabase).dbo.field1,$(SourceDatabase).dbo.field2 from
$(SourceDatabase).dbo.another_table
)
So at the end of the year all I need to change is the SourceDatabase field.
This works fine in Management Studio when I use Query>SQLCMD, but how can I achieve this when the SQL is part of a View or Stored Procedure?
Aucun commentaire:
Enregistrer un commentaire