dbTalk Databases Forums  

Creating database from stored proc with variable holding the database name

comp.databases.ms-sqlserver comp.databases.ms-sqlserver


Discuss Creating database from stored proc with variable holding the database name in the comp.databases.ms-sqlserver forum.



Reply
 
Thread Tools Display Modes
  #1  
Old   
gancy26@gmail.com
 
Posts: n/a

Default Creating database from stored proc with variable holding the database name - 08-16-2007 , 04:57 AM






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


Reply With Quote
  #2  
Old   
Erland Sommarskog
 
Posts: n/a

Default Re: Creating database from stored proc with variable holding the database name - 08-16-2007 , 05:50 AM






(gancy26 (AT) gmail (DOT) com) writes:
Quote:
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 (AT) sommarskog (DOT) se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pro...ads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinf...ons/books.mspx


Reply With Quote
Reply




Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off



Powered by vBulletin Version 3.5.3
Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.