Click here to Skip to main content
15,911,030 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
Hi,

In my software I am using SQL server as database. When my software first time installs (or runs), I need to create new database with two tables in it. Now what should I do, should I write Create Database like query by checking if database already exists or not or, there is any better way of doing this. Kindly suggest how I add database in newly installed machine.

Regards
Posted

Assuming you are talking about creating the database itself, rather than installing SQL Server, then you can run a query on your SQL Server instance which will check: that would be the safest way.

SQL
if not exists(select * from sys.databases where name = 'Testing')
    create database testing
 
Share this answer
 
Comments
[no name] 5-Nov-11 7:43am    
Hi,
How can I run query in client machines SQL Server Instance, are you talking me to write code, i.e in C#
OriginalGriff 5-Nov-11 8:15am    
Yes, write code in c# to run in the server instance. Is this a problem?
[no name] 6-Nov-11 6:26am    
No,your answer is ok for me, I was just thinking about some better approach.. but your answer clears my doubt. Thanks
thatraja 6-Nov-11 7:01am    
5!
In addition to other solutions you can deploy your DB files to destination system and commit an attach action :

First detach old one :
SQL
use master
   go
   sp_detach_db 'olddb'
   go


Then attach new one :
SQL
use master
  go
  sp_attach_db 'mydb','E:\Sqldata\mydbdata.mdf','E:\Sqldata\mydblog.ldf'
  go


read more at:
http://support.microsoft.com/kb/224071[^]

and another way is complete restore if the previous data is not important for you :

SQL
RESTORE DATABASE AdventureWorks
   FROM DISK = 'Z:\SQLServerBackups\AdventureWorks.bak'


read more :
http://msdn.microsoft.com/en-us/library/ms186858%28v=sql.90%29.aspx[^]

Both of these methods are suitable for the condition that you don't need existing data. But if you want preserve existing data it needs a deep observation of the database and applying needed changes which would be probably very complicated...
 
Share this answer
 
Comments
thatraja 6-Nov-11 7:01am    
5!
Amir Mahfoozi 6-Nov-11 7:12am    
Thanks
Jyoti Choudhury 7-Nov-11 12:41pm    
:-) Nice Answer
Amir Mahfoozi 7-Nov-11 15:35pm    
Thanks Jyoti

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