t-sqlvisual-studio-2013sql-server-data-tools

How do I use an SQLCMD variable to define a table name?


So, using SSDT on Visual Studio 2013, I can specify a Database name...

create view vSample1 as 
select * from [$(RandomDatabase)].dbo.TableName

I can also do this with a four part name

create view vSample2 as 
select * from [$(RandomServer)].[$(RandomDatabase)].dbo.TableName

But when I try to do this with the TableName, I get errors...

create view vSample3
select * from [$(RandomServer)].[$(RandomDatabase)].dbo.[$(RandomTable)]

It gives me an error similiar to

Error:  SQL71561: View: [vSample3] has an unresolved reference to object [$(RandomServer)].[$(RandomDatabase)].dbo.[$(RandomTable)].

I've been looking at the SQLCMD variables window in the project settings and have verified that the $(RandomTable) variable is defined as TableName, but it still gives me build errors.

Why is this, and how do I fix it?

Thanks


Solution

  • I would use pre/post deployment script to create such view using sp_executesql and dynamic query.

    exec sp_executesql N'create view vSample3 as
    select * from [$(RandomServer)].[$(RandomDatabase)].dbo.[$(RandomTable)]'