Creating database from stored proc with variable holding the database name

Creating database from stored proc with variable holding the database name

am 16.08.2007 11:57:03 von gancy26

Here is my code

ALTER PROCEDURE Test
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

DECLARE @From varchar(10)
DECLARE @To varchar(10)
DECLARE @DBName varchar

SELECT TOP 1 @From = CONVERT(char,CreateDate,101) FROM CustomerInfo
WHERE TicketNum =
(SELECT TOP 1 TicketNum FROM CustomerInfo
WHERE CreateDate <= DATEADD(mm, -30, CURRENT_TIMESTAMP)
ORDER BY CreateDate DESC)
SELECT @To = CONVERT(char,GETDATE(),101)

SET @DBName = 'Archive_SafeHelp'
CREATE DATABASE @DBName + ' ' + @From + ' ' + @To
END

I am trying to create a database based on the name contained in the
variables. I get the error 'Incorrect syntax near '@DBName'. How do
i accomplish this?

Thanks
Ganesh

Re: Creating database from stored proc with variable holding the database name

am 16.08.2007 12:50:44 von Erland Sommarskog

(gancy26@gmail.com) writes:
> SET @DBName = 'Archive_SafeHelp'
> CREATE DATABASE @DBName + ' ' + @From + ' ' + @To
> END
>
> I am trying to create a database based on the name contained in the
> variables. I get the error 'Incorrect syntax near '@DBName'. How do
> i accomplish this?

You need to use dynamic SQL:

SELECT @sql = 'CREATE DATABASE ' + @DBName + ' ' + @From + ' ' + @To
EXEC sp_executesql @sql

For more information on dynamic SQL, I have an article on my web site:
http://www.sommarskog.se/dynamic_sql.html



--
Erland Sommarskog, SQL Server MVP, esquel@sommarskog.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/prodtechnol/sql/2005/downlo ads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinfo/previousversions/books .mspx