0
 Use master 
    GO
    Declare @dbName As VARCHAR(50)
    SET @dbName = 'TestDB'
    CREATE DATABASE @dbName

Above sqlserver is script is giving me error. Why?

Msg 102, Level 15, State 1, Line 3
Incorrect syntax near '@dbName'.
2
  • Try this...Declare @dbName As VARCHAR(50) Declare @createdbName As VARCHAR(500) SET @dbName = 'TestDB' select @createdbName ='CREATE DATABASE'+ @dbName exec (@createdbName) Commented Nov 14, 2013 at 9:35
  • possible duplicate of How to use variable for database name in t-sql Commented Nov 14, 2013 at 10:58

2 Answers 2

1

You can not use dynamic sql and ddl as mixed. Use dynamic sql . Try this code:

Use master 
    GO
    Declare @dbName As VARCHAR(50) 
    DECLARE @Q VARCHAR(MAX)
    SET @dbName = 'TestDB'
    SET @Q='CREATE DATABASE '+ @dbName
    EXEC(@Q)
Sign up to request clarification or add additional context in comments.

Comments

0

If won't work because you're passing a VARCHAR type and for the creation of a database, it takes an object instead of a Varchar. Else, you'll need to pass the whole query as a string to execution;

Declare @dbName As VARCHAR(50) = 'TestDB'
DECLARE @Creation VARCHAR(50) ='CREATE DATABASE '+ @dbName 
EXEC(@Creation)

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.