2

I am trying to create SQL Scripts to move old data to a seperate database. The problem I have right now is that I want to name the Database from an SELECT statement.

use DBName;
declare @release varchar(max)
set @release = concat('Release_',(select MetaRevision from metarevision))
select @release

if db_id(@release) is null create database @release

Sadly this does not work. I get the following error:

Incorrect syntax near '@release'

Is there a way to name a Database from an Select Statement?

5
  • 2
    exec ('create database ' + quotename(@release)) or something like that. Commented Jun 6, 2018 at 8:27
  • To explain why: the parameter to create database is a name, not a string/varchar. In other words, create database XYZ is correct, while create database 'XYZ' isn't - and that is why also create database @release is not allowed. Commented Jun 6, 2018 at 8:32
  • as @ta.speot.is suggested you need Dynamic SQL for this Commented Jun 6, 2018 at 8:33
  • Is there a workaround? 'quotename' dose not work. Commented Jun 6, 2018 at 8:35
  • declare @release nvarchar(10) = 'abc'; declare @sql nvarchar(100) = 'create database ' + quotename(@release); exec (@sql); or something like that. Commented Jun 6, 2018 at 8:39

2 Answers 2

1

Thanks for your help. I found a solution with the information of ta.speot.is and p.campbell.

For the future, this is the solution:

use DBName;
declare @release varchar(14)
set @release = concat('Release_',(select MetaRevision from metarevision))

declare @quoted varchar(16);
set @quoted =  quotename(@release);

if db_id(@release) is null exec ('create database ' + @quoted)
Sign up to request clarification or add additional context in comments.

Comments

1

You can just do it like this

declare @release varchar(max)
set @release = concat('Release_','TestOst') //Replace TestOst with your metadata
select @release

if db_id(@release) is null 

declare @SQL nvarchar(max)

SET @SQL = 'create database '+quotename(@release)

exec(@SQL)

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.