Tuesday, March 5, 2013

How to create database dynamically in sqlserver


 
DECLARE @Query VARCHAR(MAX)=''
DECLARE @DbName VARCHAR(400)  
set @DbName= @DatabaseName
SET @Query = @Query + 'CREATE DATABASE '+@DbName +' ON  PRIMARY '
SET @Query = @Query + '( NAME = '''+@DbName +''', FILENAME = '''+@DbFilePath+@DbName +'.mdf'' , SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB ) '
SET @Query = @Query + ' LOG ON '
SET @Query = @Query + '( NAME = '''+@DbName +'_log'', FILENAME = '''+@DbFilePath+@DbName +'_log.ldf'' , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)'
exec(@query)
set @Query='USE ['+@DbName+']'+' '+'CREATE TABLE [dbo].[tablename]([ID] [int] IDENTITY(1,1) NOT NULL,[col1] [nvarchar](250) NOT NULL,[clo2] [nvarchar](250) NOT NULL,[col3] [nvarchar](250) NOT NULL,[col4] [int] NOT NULL,[col5] [datetime] NOT NULL,[col6] [int] NULL,[col7] [datetime] NULL,[IsDeleted] [bit] NOT NULL,CONSTRAINT [PK_col1] PRIMARY KEY CLUSTERED([ID] ASC)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]) ON [PRIMARY]'  
print @query
exec(@query)
 

No comments:

Post a Comment