sql script to create a new database - database

I have following script.
I don't know how to create new database in sql server 2005.
I run following script, and it create tables under model instead of seperate database. it look massy.
how can I create separate database.
I am copy some script here for your adive and course of action.
-----------------------------------------------------------
-- SQL Server 2000 Bible
-- Hungry Minds
-- Paul Nielsen
-- OBX Kites sample database - CREATE Database, Tables, and Procs
-- this script will drop an existing OBXKites database
-- and create a fresh new installation
-- related scripts:
-- OBXKites_Populate
-- T-SQL KEYWORDS go
-- DatabaseNames
-----------------------------------------------------------
-----------------------------------------------------------
-- Drop and Create Database
USE master
GO
IF EXISTS (SELECT * FROM SysDatabases WHERE NAME='OBXKites')
DROP DATABASE OBXKites
go
-- This creates 1 database that uses 2 filegroups
CREATE DATABASE OBXKites
ON PRIMARY
(NAME = 'OBXKites', FILENAME = 'D:\SQLData\OBXKites.mdf'),
FILEGROUP Static
(NAME = 'OBXKitesStatic', FILENAME = 'c:\SQLData\OBXKitesStatic.ndf')
LOG ON (NAME = 'OBXKitesLog', FILENAME = 'c:\SQLData\OBXKites.ldf')
go
-- set to Full Log
go
SET QUOTED_IDENTIFIER ON
go
USE OBXKites
go
-----------------------------------------------------------
-----------------------------------------------------------
-- Create Tables, in order from primary to secondary
CREATE TABLE dbo.OrderPriority (
OrderPriorityID UNIQUEIDENTIFIER NOT NULL ROWGUIDCOL DEFAULT (NEWID()) PRIMARY KEY NONCLUSTERED,
OrderPriorityName NVARCHAR (15) NOT NULL,
OrderPriorityCode NVARCHAR (15) NOT NULL,
Priority INT NOT NULL
)
ON [Static]
go

CREATE DATABASE OBXKites
ON PRIMARY
(NAME = 'OBXKites', FILENAME = 'D:\SQLData\OBXKites.mdf'),
FILEGROUP Static
(NAME = 'OBXKitesStatic', FILENAME = 'c:\SQLData\OBXKitesStatic.ndf')
LOG ON
(NAME = 'OBXKitesLog', FILENAME = 'c:\SQLData\OBXKites.ldf')
go
This code in your script should create a new database. If no error occurrs in the process.

Can you simplify it down? or do you have to do all of that checking?
If it can be simplified I beileve some code such as:
CREATE DATABASE OBXKites
USE OBXKites
CREATE TABLE OrderPriority(syntax)
If simple code like this doesn't work, you may have deeper issues with rights or files or something as suggested by queen3 just before me.
Afterthought: At my school we were having issues like this as well I believe... after a few classes we finally arived at the conclusion that we didn't have rights to add files to the program files directory on the lab computers and SQL wasn't reporting the error to us.

Are there any errors in output? The script itself does already do what you requested.
I'd suspect that you incorrectly specified filenames - some of them are on drive C:, and some on drive D:.

Your script in question will create the tables in the OBXKites database (see the USE OBXKites statement in your script)
Does the OBXKites database already exist in your server instance? If so, that's probably why it appears that it is creating the tables in the current database, since the script is effectively removing and recreating the OBXKites database. If you need a different name for the database, find all instances of "OBXKites" in your script above after the line that reads "This creates 1 database that uses 2 filegroups" and rename it to the new database name you desire.
The only other option could be that the script has execution errors creating the database, if your user account lacks the proper permissions to do so. However, the script continues to execute, creating the tables in the current database you are logged in to, which is why you are seeing the tables there.

Create DataBase In Ubuntu Terminal
my database name is database_name
you can use anything
create database database_name;
How to select this database to create a table inside it.
use database_name;

Related

Undocumented SmoScriptOption: ScriptForAlter and ScriptForCreateDrop

scrp.Options.ScriptForAlter -- I suppose it scripts an ALTER TABLE instead of a CREATE TABLE
scrp.Options.ScriptForCreateDrop -- I'd guess it scripts a DROP TABLE and only afterwards a CREATE TABLE ?
My DB is fairly large and I'm still using Management Studio for script generation, so I'd like to know if someone else already found out the meaning of those options.

Trying to attach mdf file to localDb throws error at least one file is required

TITLE: Microsoft SQL Server Management Studio
Attach database failed for Server '(localdb)\mssqllocaldb'. (Microsoft.SqlServer.Smo)
ADDITIONAL INFORMATION:
At least one file is needed for Database Attach. (Microsoft.SqlServer.Smo)
I am trying to attach this .mdf database file to my LocalDb instance. It's fine if I can to it to SQL Server too. I have .ldf file in the same directory
For completion's sake - Jim's comment solves (half) the problem and gets you going.
The other "half" of the problem is - what if you ultimately want to rename the physical database file? The answer is available in this CodeProject post.
Steps:
ALTER DATABASE to set the new physical filenames (data file and log file)
Won't take effect until SQL Server is restarted or the database taken offline and brought back online
ALTER DATABASE [CurrentName] MODIFY FILE (NAME = 'CurrentName', FILENAME = '<Full-Path-Required>\NewDbName.mdf');
ALTER DATABASE [CurrentName] MODIFY FILE (NAME = 'CurrentName_log', FILENAME = '<Full-Path-Required>\NewDbName_log.ldf');
ALTER DATABASE again to set new logical file names (again, data and log files)
Takes effect immediately
ALTER DATABASE [CurrentName] MODIFY FILE (NAME = 'CurrentName', NEWNAME = 'NewDbName');
ALTER DATABASE [CurrentName] MODIFY FILE (NAME = 'CurrentName_log', NEWNAME = 'NewDbName_log');
Take offline and bring back online or restart SQL Server
Using SQL Server Management Studio:
Right-click on the renamed database and click Take Offline under Tasks.
Right-click on the (offline) database and click Bring Online under Tasks.
Using T-SQL:
ALTER DATABASE [CurrentName] SET OFFLINE WITH ROLLBACK IMMEDIATE; (sets it to offline and disconnects any clients)
ALTER DATABASE [CurrentName] SET ONLINE;
Full code:
-- Find "CurrentName" (without quotes) and replace with the current database name
-- Find "NewDbName" (without quotes) and replace with the new database name
USE [CurrentName];
-- Change physical file names:
ALTER DATABASE [CurrentName] MODIFY FILE (NAME = 'CurrentName', FILENAME = '<Full-Path-Required>\NewDbName.mdf');
ALTER DATABASE [CurrentName] MODIFY FILE (NAME = 'CurrentName_log', FILENAME = '<Full-Path-Required>\NewDbName_log.ldf');
-- Change logical names:
ALTER DATABASE [CurrentName] MODIFY FILE (NAME = 'CurrentName', NEWNAME = 'NewDbName');
ALTER DATABASE [CurrentName] MODIFY FILE (NAME = 'CurrentName_log', NEWNAME = 'NewDbName_log');
-- Take offline and back online
USE [master]
GO
ALTER DATABASE [CurrentName] SET OFFLINE WITH ROLLBACK IMMEDIATE;
-- Then navigate to <Full-Path-Required> and rename the files
ALTER DATABASE [CurrentName] SET ONLINE;
If you don't recall the previous filenames, open the .mdf file in a hex editor and at around offset 0x19D you'll see a UTF-16 (2 byte/char) string of that filename
None of these answers were quick to the point answers so I thought I would just add my answer to point out my findings (based off of everyone's contributions here)...
The Situation:
You have a database file and a log file but not a backup of them. You are trying to ATTACH the database (more than likely in an effort to recover from a server that went down).
The Problem:
You have changed the name of the MDF and LDF files to something different than they were originally. You need to rename them back to the original names then try to ATTACH.
How To Rename the DB files (the easy way):
After you have ATTACHED the MDF and LDF files successfully you then
want to make a BAK (backup) file by backing up the database.
Next you want to drop/delete the database from the SQL server.
Next you want to RESTORE the database. This is where you can go into the
FILES section (on left) that will let you change the Restore As
file name to what you want the MDF and LDF files to be named as.
I would then go ahead and make ANOTHER backup of that new database
again so that this time the backup contains the correct file names
you want.
I've had to move/rename DBs several times. In case you're in the same boat, here's a script that uses variables to avoid typing the new/old names over and over.
It uses the same logic from Jesse's answer, other than automatically starting the DB back up for you. I assume you need to turn it back on after moving/renaming the physical files, hence the removal of that statement. Please comment if this assumption is incorrect.
However, to reflect the logical rename in SSMS, you still need to right click -> rename. That appears to be the same without using the EXECUTE/REPLACE method below.
---------- CHANGE THESE ----------
-- Keep names identical to only move locations
DECLARE #CurrDbName AS varchar(255) = 'CurrentDbName'
DECLARE #NewDbName AS varchar(255) = 'NewDbName'
DECLARE #PathToFolder AS varchar(255) = '<FullPathMinusFilename>\'
---------- DECLARE TEMPLATES ----------
-- Use DB
DECLARE #USE_DB AS varchar(255) = 'USE [{CurrDbName}]'
-- Change physical file names
DECLARE #SET_PHYS_MDF AS varchar(255) = 'ALTER DATABASE [{CurrDbName}] MODIFY FILE (NAME = ''{CurrDbName}'', FILENAME = ''{PathToFolder}{NewDbName}.mdf'')'
DECLARE #SET_PHYS_LDF AS varchar(255) = 'ALTER DATABASE [{CurrDbName}] MODIFY FILE (NAME = ''{CurrDbName}_log'', FILENAME = ''{PathToFolder}{NewDbName}_log.ldf'')'
-- Change logical names (LOG = "logical", not "log")
If (#CurrDbName != #NewDbName)
BEGIN
DECLARE #SET_LOG_MDF AS varchar(255) = 'ALTER DATABASE [{CurrDbName}] MODIFY FILE (NAME = ''{CurrDbName}'', NEWNAME = ''{NewDbName}'')'
DECLARE #SET_LOG_LDF AS varchar(255) = 'ALTER DATABASE [{CurrDbName}] MODIFY FILE (NAME = ''{CurrDbName}_log'', NEWNAME = ''{NewDbName}_log'')'
END
-- Take offline
DECLARE #SET_OFFLINE AS varchar(255) = 'ALTER DATABASE [{CurrDbName}] SET OFFLINE WITH ROLLBACK IMMEDIATE'
---------- START DOING STUFF ----------
DECLARE #SQL_SCRIPT AS varchar(255)
-- Use DB
SET #SQL_SCRIPT = REPLACE(#USE_DB, '{CurrDbName}', #CurrDbName)
EXECUTE (#SQL_SCRIPT)
-- Change physical file names
SET #SQL_SCRIPT = REPLACE(REPLACE(REPLACE(#SET_PHYS_MDF, '{CurrDbName}', #CurrDbName), '{NewDbName}', #NewDbName), '{PathToFolder}', #PathToFolder)
EXECUTE (#SQL_SCRIPT)
SET #SQL_SCRIPT = REPLACE(REPLACE(REPLACE(#SET_PHYS_LDF, '{CurrDbName}', #CurrDbName), '{NewDbName}', #NewDbName), '{PathToFolder}', #PathToFolder)
EXECUTE (#SQL_SCRIPT)
-- Change logical names (LOG = "logical", not "log")
If (#CurrDbName != #NewDbName)
BEGIN
SET #SQL_SCRIPT = REPLACE(REPLACE(#SET_LOG_MDF, '{CurrDbName}', #CurrDbName), '{NewDbName}', #NewDbName)
EXECUTE (#SQL_SCRIPT)
SET #SQL_SCRIPT = REPLACE(REPLACE(#SET_LOG_LDF, '{CurrDbName}', #CurrDbName), '{NewDbName}', #NewDbName)
EXECUTE (#SQL_SCRIPT)
END
-- Take offline
USE [master]
SET #SQL_SCRIPT = REPLACE(#SET_OFFLINE, '{CurrDbName}', #CurrDbName)
EXECUTE (#SQL_SCRIPT)
-- Now turn off the database, rename/move physical files, and bring the database back online
This is my first answer, apologies if it's not of sufficient quality.
Command line turned out to be much more forgiving with the renamed files. Note that this isn't a fire-and-forget script...run each portion separately, paying attention to the names that need to be changed:
--#1 Attach the db
USE [master]
GO
CREATE DATABASE RenamedDB ON
( FILENAME = N'<PathToRenamedFile>\renamedDBFile.mdf' ),
( FILENAME = N'<PathToRenamedFile>\renamedDBFile_log.ldf' )
FOR ATTACH
GO
--#2 Get the old logical file names:
USE RenamedDB
select * from sys.database_files
--#3 Rename the old logical files
ALTER DATABASE RenamedDB MODIFY FILE (NAME=N'OldLogicalDBName', NEWNAME=N'renamedDBFile')
GO
ALTER DATABASE RenamedDB MODIFY FILE (NAME=N'OldLogicalLogName', NEWNAME=N'renamedDBFile_log')
GO
--#4 check for the new names
select * from sys.database_files

Query to create a new table to a specific database in SQL?

I have 3 databases sytemdatabases,smoketest and learnqueries .
Every time i write and execute create table query (create table tablename (colname datatype(size))), a new table is created in the systemdatabases.
I need it to be created to smoketest database.
I tried on this query (create table smoketest.newtablename(number int,name varchar(50));
It is showing an error (Msg 2760, Level 16, State 1, Line 1
The specified schema name "smoketest" either does not exist or you do not have permission to use it.) when i executed it.
It says 2 chances
Database does not exist - but the database exists
Does not have permission - what does it mean -how to set permission to create a
new table to a specific database
Pls help
The 4 part 'dot' notation in Sql Server for tables is
Server.Database.Schema.Object
So you would need to create the table with at least 3 parts if smoketest is not the current database on your connection, e.g. if you are on master, and assuming you want the new table in schema dbo:
create table smoketest.dbo.Tablename(ID INT)
Alternatively, switch to the smoketest database and create the table with 1 or 2 part naming:
use smoketest
GO
create table dbo.Tablename(ID INT)
GO
USE smoketest
GO
create table newtablename(number int,name varchar(50));
If you have a permission issue, check out this SQL Server 2008: how do I grant privileges to a username?
Hope this helps.

How can I create backup script from diagram in SQL Server?

I use SQL Server 2012 and SQL Server 2008 R2.
I create a script from all object (tables / trigger / stored procedure / function ...) in my database.
I generated this script from SQL Server Management Studio. I can recreate my database with this scrips on the other server. But I miss all diagrams of my database after run my script for create another database.
Therefore, I need create backup script from all diagrams that exist in my database.
I need execute this script on the destination database for recreating all my diagrams.
I found this Link. but i need some thinks that create all script (Insert Command) automatically.
I have found a reasonable solution. The problem is that Management Studio cannot display more that 65535 characters for Non-XML data, and cannot be set to display more than 65535.
See code for documentation :)
Backup script:
-- 1. Read from DB, using XML to workaround the 65535 character limit
declare #definition varbinary(max)
select #definition = definition from dbo.sysdiagrams where name = 'ReportingDBDiagram'
select
'0x' + cast('' as xml).value('xs:hexBinary(sql:variable("#definition") )', 'varchar(max)')
for xml path('')
-- 2. Open the result XML in Management Studio
-- 3. Copy the result
-- 4. Paste this in backup script for #definition variable
Restore script:
declare #definition varbinary(max)
set #definition = 0xD0CF -- Paste 0x0 value from Backup script
-- Create diagram using 'official' Stored Procedure
exec dbo.sp_creatediagram
#diagramname = 'ReportingDBDiagramCopy',
#owner_id = null,
#version = 1,
#definition = #definition
Scripting your database does not include diagrams as they are not server objects in the same way as a table or stored procedure; they exist as data in the sysdiagrams table.
A similar question on SO asked How do you migrate SQL Server Database Diagrams to another Database?
The accepted answer is to copy the contents of the sysdiagrams table to the new database, so you could include the table contents in your script. The answer with the most up-votes has a link to a way of scripting diagrams.
I've tried backing up and then restoring a database to the same server, deleting the diagram I had created (I only had one) and then running the following query:
INSERT INTO database2.dbo.sysdiagrams
(
NAME
,principal_id
,version
,DEFINITION
)
SELECT NAME
,principal_id
,version
,DEFINITION
FROM database1.dbo.sysdiagrams
The diagram was successfully restored, however I did do this on a restored backup, I should really test it with a new database generated from a script.
UPDATE:
I scripted a database and then created a new database from it. When trying to rebuild the diagrams using an INSERT statement I got the error
So although it seems possible it's not trivial to create diagrams in a new database created from a script. Go with the answer given regarding scripting diagrams and modify it for your own needs.
Perhaps you can investigate further and post your own answer :)
Here's a quick & dirty method I use. Since the query window won't display the full varbinary(max) value of the definition field, but the XML editor will, I output the rows to XML as follows:
Run the following query on the server/database that contains the diagrams:
SELECT 'INSERT sysdiagrams(name,principal_id,diagram_id,version,definition) VALUES('''+name+''','
+CONVERT(varchar(2),principal_id)+','+CONVERT(varchar(2),diagram_id)+','+CONVERT(varchar(2),version)+','
+'0x' + CAST('' as xml).value('xs:hexBinary(sql:column("definition"))','varchar(max)') +')'
FROM RCSQL_ClaimStatus.dbo.sysdiagrams
FOR XML PATH
Click on the generated link to open the XML result, and ctrl-a & ctrl-c to copy all rows generated.
Paste that output back into your query window. I usually paste it between a pair of IDENTITY_INSERT's like this:
--TRUNCATE TABLE sysdiagrams
SET IDENTITY_INSERT sysdiagrams ON;
<row>INSERT sysdiagrams(name,principal_id,diagram_id,version,definition) VALUES('ERD1',1,1,1,0xD0CF11E0A1B11AE100000...)</row>
<row>INSERT sysdiagrams(name,principal_id,diagram_id,version,definition) VALUES('ERD2',1,2,1,0xD0CF11E0A1B11AE100000...)</row>
<row>INSERT sysdiagrams(name,principal_id,diagram_id,version,definition) VALUES('ERD3',1,3,1,0xD0CF11E0A1B11AE100000...)</row>
SET IDENTITY_INSERT sysdiagrams OFF;
Remove the row & /row XML tags from your inserts, and run them on the target server. You can truncate the sysdiagrams table if you're replacing all values with new values.

How to execute the Entity Framework Model First DDL File on a SqlServer Compact database?

here is something that look easy but drives me crazy since days...
I´m trying to create an application with Entity Framework and Sql Server Compact.
I want to use model first approach.
I created a edmx file for the model and runned the Database Generation wizard which produced an edmx.sqlce file that contains the Table Creation commands.
But where to run this edmx.sqlce file?
I tried to run the file by sending the content to the ExecuteNonQuery Command of the SqlCommand. But it also gives syntax errors - But why should the generated edmx.sqlce file be corrupt??? I think i have to run the file somewhere else.
Can anyone tell me where? (I only have an C# express version).
The content of the edmx.sqlce file is:
-- --------------------------------------------------
-- Entity Designer DDL Script for SQL Server Compact Edition
-- --------------------------------------------------
-- Date Created: 07/27/2011 23:50:28
-- Generated from EDMX file: C:\Users\Ralf\Programmierung\MySoftware\MySoftware\MySoftwareDatenbank\MySoftwareDataModel.edmx
-- --------------------------------------------------
-- --------------------------------------------------
-- Dropping existing FOREIGN KEY constraints
-- NOTE: if the constraint does not exist, an ignorable error will be reported.
-- --------------------------------------------------
-- --------------------------------------------------
-- Dropping existing tables
-- NOTE: if the table does not exist, an ignorable error will be reported.
-- --------------------------------------------------
DROP TABLE [DataSourceSet];
GO
-- --------------------------------------------------
-- Creating all tables
-- --------------------------------------------------
-- Creating table 'DataSourceSet'
CREATE TABLE [DataSourceSet] (
[Id] int IDENTITY(1,1) NOT NULL
);
GO
-- --------------------------------------------------
-- Creating all PRIMARY KEY constraints
-- --------------------------------------------------
-- Creating primary key on [Id] in table 'DataSourceSet'
ALTER TABLE [DataSourceSet]
ADD CONSTRAINT [PK_DataSourceSet]
PRIMARY KEY ([Id] );
GO
-- --------------------------------------------------
-- Creating all FOREIGN KEY constraints
-- --------------------------------------------------
-- --------------------------------------------------
-- Script has ended
-- --------------------------------------------------
My Environment is:
- SqlServerCompact 3.5
- Visual C# 2010 Express
You shouldn't have to run the DDL script manually, it should be done automatically for you the first time you create a DbContext in code that is correctly associated with the desired database connection. I'm not as familiar with model first as I am with code first, but I understand SQL Server CE 4 is better supported by EF 4.1.
If, for whatever reason, you still want to execute the DDL script manually via ExecuteNonQuery, you'd want to remove all batch terminators ("GO"), as ExecuteNonQuery doesn't support batch queries.
My guess that Model-first approach is a stumbling-stone for SQL CE database. Too much problems with database shema changing and DB architecture.
There is one tool for VS2010 <Entity Designer Database Generation Power Pack> However its no longer supported.
Another usefull extension <SQL Server Compact/SQLite Toolbox> for VS 2010-2015 There is build-in sql editor where you can try to run edmx.sqlce file. Although, before running your script file you need to get rid of GO and Alter table instructions to make it run
Or you can use third-party software like SQL CE Database Editor

Resources