Click here to Skip to main content
15,879,348 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hii ,

i have to run create table query on group of few databases same query ... How can i do that ..

say example i have 7 databases among those there are 4 databases on which i want to fire this create statement at once how can i do that ??
Posted
Updated 29-Apr-14 2:32am
v2
Comments
CHill60 29-Apr-14 8:38am    
Are they all on the same sql server instance?
Torakami 30-Apr-14 0:56am    
yehh .. they are on same server..
Sanket Saxena 29-Apr-14 8:49am    
Agreed with CHill60's comment.If all are on same server then we can.
Torakami 5-May-14 2:58am    
Can yu please suggest ... my databases are on same server

 
Share this answer
 
v2
Try this assuming all databases are on the same instance.

SQL
DECLARE @DATABASE TABLE
(
	ID INT IDENTITY(1, 1),
	NAME VARCHAR(100)
)

INSERT INTO @DATABASE (NAME)
SELECT 'Adventure' 
UNION ALL
SELECT 'TESTDB'

DECLARE @INDEX INT, @TOTAL INT, @DBNAME VARCHAR(100)

SELECT @INDEX = 1
SELECT @TOTAL = COUNT(*) FROM @DATABASE


WHILE @INDEX <= @TOTAL
BEGIN

	SELECT @DBNAME = NAME
	FROM	@DATABASE
	WHERE	ID = @INDEX
	
	SELECT 'USE ' + @DBNAME, @INDEX
	
	EXECUTE ('USE ' + @DBNAME)
	
	EXECUTE ('CREATE TABLE ' + @DBNAME + '..TEST1	(NAME VARCHAR(100)) ')
	 

	SET @INDEX = @INDEX + 1 

END
 
Share this answer
 
Assuming you can connect to all of the databases, and taking your 'create all at once' as literally as possible, I suggest a stored procedure.

Such a procedure would allow you to handle this almost concurrently (if you to do this with multiple sets of tables and if you have such a need) depending upon how/if you use parameters.


An example of how to write a basic procedure for creating the table is:
Here^

Note that creating a table via a stored procedure isn't normally done. I'm suggesting this to make it essentially a batch process.
 
Share this answer
 
v2
Comments
Torakami 5-May-14 2:57am    
The link you have given is not at all usefull .. can u please suggest me anything else .. in that link explanation or example is not proper

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900