1

I want to create databases in SQL Server 2012 with this script

DECLARE @userdb varchar(30)
SET @userdb = 'DB_testing'

CREATE DATABASE @userdb

but I get this error message

Msg 102, Level 15, State 1, Line 3
Incorrect Syntax near '@userdb'

What am I doing wrong?

3 Answers 3

3

you have to use dynamic SQL

 declare @userdb varchar(30)
 SET @userdb = 'DB_testing'

 declare @sql nvarchar(111);
 set @sql = 'create database  '+ @userdb 

 Exec (@sql)
Sign up to request clarification or add additional context in comments.

Comments

3

You can either use dynamic SQL as shown in the other answers or you can use SQLCMD.

:SETVAR userdb "DB_testing"

CREATE DATABASE $(DB_userdb)

Comments

1

You can not pass variable into basic CREATE DATABASE statement, you will need dynamic SQL

declare @sql varchar(30) @userdb varchar(30)
SET @userdb = 'DB_testing'
SET @sql = 'create database ' + QUOTENAME(@userdb)
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.