December 13, 2010 at 8:13 am
Hii all, my requirement is in a stored procedure I have to create a database dynamically and add some objects to the newely created database. Am successfull in 1st part but am not able to use that database in the same procedure for creating some db objects.
When I try "Use databasename" it is throwing some error.
Can any one help me in this regard.
December 13, 2010 at 8:58 am
Can you provide the error
What objects do you want to create
If you want to create tables then you could do it like this
declare @useBase nvarchar(max)
set @useBase = 'create table Test.dbo.Test(ID int,VarID nvarchar(max))'
exec sp_executesql @useBase
December 13, 2010 at 10:04 am
Actually this is wat am trying to do
CREATE PROCEDURE AAA
AS
BEGIN
CREATE DATABASE DB_USERS;
USE DB_USERS;
CREATE TABLE ADMINUSER (ID INT,UNAME VARCHAR(40),PWD VARCHAR(40));
--IN THE SAME WAY LOT OF TABLES AND PROCEDURES
END
and am getting the following error
Msg 154, Level 15, State 1, Procedure AAA, Line 6
a USE database statement is not allowed in a procedure, function or trigger.
December 13, 2010 at 2:49 pm
You cannot do this. You would either need to create the tables with the proper database name as I've done with dynamic SQL, or run a pre-written script. If the table names are known, you can then easily load that script and run if from something like SQLCMD or as an SSIS package, with the proper database context.
A stored procedure is built to be a method of code execution, not as a container for creating other objects. Certain creation statements need to be in their own batch, which you cannot do in a stored procedure.
Viewing 5 posts - 1 through 4 (of 4 total)
You must be logged in to reply to this topic. Login to reply