How Do I Initialize an Existing Microsoft SQL Server Database? - sql-server

I have a database which has users assigned against it. I want to initialize the database (as though I'd just created it) rather than creating a new one, naming it appropriately, and re-adding all of the users.
Is it possible to completely reinitialize/reset a database?
Is it possible to do (1) whilst retaining the users and their permissions?
Thanks for looking :)

You can use generate script to create SQL file with Schema and user information.
Rename the existing db and run the script to create new one. Generate script provides lot of options to customize the script according to your needs
Right click on db -> Tasks -> Generate script -> Click next on the
wizard
Enable 'script logins' in Choose script options section of
the wizard
Select the users
Generate the script

Related

How to create database using Database Project in Visual Studio if doesn't exists?

I have a Database project for my personal project and I am trying to deploy my code to my DEV server. I frequently delete and re-create my DEV Server. Right now, DEV Server is newly created with SQL Server. Every time I want to deploy my code I have to manually create Database Project and then publish database project. I want to automate creation of Database with database project deployment.
Right now, I have a script that creates database, but I have to execute it manually. And this is working perfectly but I want to automate this step as well.
Is this even possible? If yes, then how? Please explain step by step. Also what will we mention for Initial Catalog in connection string?
Edit:
I tried to create Database by using
CREATE DATABASE LocalDbTest
in Pre-Deployment Script. But it didn't work. It is creating Database, but then tables are not getting created tables under it. Since I used master database as default database, it is creating table under master. It is not letting me select LocalDbTest database as default because it is not yet created, so I have to select Master as my default database. I tried to Change Database by:
USE LocalDbTest
GO
I used it just after creating Database but this didn't work because when generating script it is changing back to default database. This part is coming automatically when generating script.
USE [$(DatabaseName)];
GO
Also Visual Studio is not letting me add database name in front of table name like:
CREATE TABLE [LocalDbTest].[dbo].[TestTable]
I am getting error:
When you create an object of this type in a database project, the object's name must contain no more than two parts.
If you have a script ready for database creation, you can use the Pre-build event to call SQLCMD and run your script.
Edit:
If you have trouble pointing to a database that does not exist, you may have to manually edit the publish profile (ex. dev.publish.xml) and set the TargetDatabaseName element explicitly. You can also set CreateNewDatabase element to True if you want to be recreated every time it gets published.
Answer:
You can use a publish profile and hardcode the target database in it.

Can I manage database using database project without knowing connection string?

I have created database project. I am able to upgrade my changes in my sql server. Now I have deploy the same changes on another environment. Also I dont want to change my previous data. I dont have to access that Sql server so I don`t know the connection string.
I have some options, like to deploy the .dacpac file or .sql script, but it first delete the database then creates new one. So that I loosing my data.
Please help me. If any option is there?
The options I see for this are:
Ask for a backup (or extract schema tables using task-->Generate scripts ion ssms) - restore this somewhere and use sqlpackage to generate a deployment script you can ask them to run
Ask them to run sqlpackage.exe and either generate a script or run it directly
Ask them for permissions so you can do it
If the database is being deleted then you have the option "CreateNewDatabase" set to true which would be bad in a production environment so remove it or set it to false!
If they run it or you ask for permissions, these are the minimum permissions you need to generate a script (to run the script you will probably need dbo):
https://the.agilesql.club/Blogs/Ed-Elliott/What-Permissions-Do-I-Need-To-Generate-A-Deploy-Script-With-SSDT (my blog)

Insert table data from table to another table

I'm trying to insert from one database to another using SQL Server 2008.
I'm trying to insert from 'EG-COMPUTER1\FTLIVE' to 'EG-COMPUTER2\FTSTANDBY'.
Basically from a database on one computer to the same database on a different computer which is on the same network.
How would I able to do this?
Note: I can connect to both databases on the same computer so there must be an easy way to insert from one database to another?
EDIT::
Just to add that one computer is using SQL Server 2008-R2 and the other is using SQL Server 2008
There are several ways you can do this.
1. RightClick On DataBase -> Tasks -> Import -> Import Export wizard ->Choose Source database -> choose Destination database -> choose Copy data from One or more table -> choose required tables -> Import.
2.RighClick On Database -> Task -> Generate Script -> Choose tables -> Advanced -> Change "Types of Data to Script " to "Schema and Data or data or schema(as required)" -> Change "script Drop and Create" to Drop and Create(optional) - > create.
Copy the script file/files and run in the other computer.
3.Right Click the database -> task -> BackUp -> create backup -> take the back up to other computer(.bak file can be found inside the Backup directory inside installation directory) -> right click the database -> task -> restore -> choose the bakup file -> done.
4. Can use sql azure migration tool http://sqlazuremw.codeplex.com/ (similar to step 1)
If you would like to just use the database level transfer of data then you should configure those two instances as linked servers (msdn doc).
Otherwise, if you are familiar with Java (or any high level language that provides APIs to interact with databases), you can write a simple program that retrieves the data from the table in one server and inserts into the table in the other server (quicker way without reaching out to DBAs to configure linked servers).
I've found what I need to do, this is:
INSERT INTO [DatabaseNameA].[dbo].[Table]
([Column1],[Column2] etc...)
SELECT
[Column1],[Column2] etc...
SET IDENTITY_INSERT [DatabaseNameB].[dbo].[Table] On;
GO
This will select the database I want to select from, turn the identity_insert to on so the data can be inserted and transfer the data from one database to another.
Nislva ,
kindly verify both tables are acessable or not with your login. if both tables are acessable then try to copy of one database table to another database table other wise create one view from one database table and transfer that view to another database table.
there after you can do your required task. this is best practice method and in future also you may not get performance problems.
if you are not intrested to do this task then simply follow the below query
insert into ur-tablename(column-names)
select sourcedbname.schemaname.column-name1 , sourcedbname2.schemaname.column-name ...
from sourcedatabsename.schemaname.tablename
You can either use OpenRowSet if this is not a recurring activity otherwise if you need to perform actions frequently then you should create linked server.

How do I export my views from a database?

I have a number of views in my SQL Server database.
How do I export these as CREATE VIEW scripts?
I tried to right click the database - script database as - create to - new query editor window, but it doesn't show my my views (or tables even for that matter).
Any ideas?
In SSMS, if you right click the DB -> Tasks -> Generate Scripts... - that will take you through a wizard.
You can run through the wizard and select your DB, then the views as AdaTheDev mentioned or you can right click on each query and generate a script directly.
I prefer another way, because always I edit the views to remove "not necessary script generated SQL syntax" (depends on the point of view :)).
Right click the view, Generate script, CREATE in, new window.
See screenshot below (sorry for german version, but should work anyway).
I tried to right click the db - script database as - create to - new query editor window, but it doesn't show my my views (or tables even for that matter).
The purpose of the menu you mentioned is only to create the empty database, without any tables, views or anything else.
If you want to script anything beyond the empty database, you have to use the wizard already mentioned in AdaTheDev's answer.
Maybe you receive empty page because source of VIEW was encrypted or removed.
In older SQL editions there was a trick - after creating VIEW (SQL Server compiled it) developer could remove source of VIEW statement to protect it from "deassemblation". In current editions there is possibility to encrypt source of VIEW statement.

How can I use a SQL Scripts in a Database Project with the System.Data.SQLite data provider?

I've got a project where I'm attempting to use SQLite via System.Data.SQLite. In my attempts to keep the database under version-control, I went ahead and created a Database Project in my VS2008. Sounds fine, right?
I created my first table create script and tried to run it using right-click->Run on the script and I get this error message:
This operation is not supported for the provider or data source you are using.
Does anyone know if there's an automatic way to use scripts that are part of database project against SQLite databases referenced by the databases, using the provider supplied by the System.Data.SQLite install?
I've tried every variation I can think of in an attempt to get the script to run using the default Run or Run On... commands. Here's the script in it's most verbose and probably incorrect form:
USE Characters
GO
IF EXISTS (SELECT * FROM sysobjects WHERE type = 'U' AND name = 'Skills')
BEGIN
DROP Table Skills
END
GO
CREATE TABLE Skills
(
SkillID INTEGER PRIMARY KEY AUTOINCREMENT,
SkillName TEXT,
Description TEXT
)
GO
Please note, this is my first attempt at using a Database, and also the first time I've ever touched SQLite. In my attempts to get it to run, I've stripped any and everything out except for the CREATE TABLE command.
UPDATE: Ok, so as Robert Harvey points out below, this looks like an SQL Server stored procedure. I went into the Server Explorer and used my connection (from the Database project) to get do what he suggested regarding creating a table. I can generate SQL from to create the table and it comes out like thus:
CREATE TABLE [Skills] (
[SkillID] integer PRIMARY KEY NOT NULL,
[SkillName] text NOT NULL,
[Description] text NOT NULL
);
I can easily copy this and add it to the project (or add it to another project that handles the rest of my data-access), but is there anyway to automate this on build? I suppose, since SQLite is a single-file in this case that I could also keep the built database under version-control as well.
Thoughts? Best practices for this instance?
UPDATE: I'm thinking that, since I plan on using Fluent NHibernate, I may just use it's auto-persistence model to keep my database up-to-snuff and effectively in source control. Thoughts? Pitfalls? I think I'll have to keep initial population inserts in source-control separately, but it should work.
I built my database using an SQLite SQL script and then fed that into the sqlite3.exe console program like this.
c:\sqlite3.exe mydatabase.db < FileContainingSQLiteSQLCommands
John
Well, your script looks like a SQL Server stored procedure. SQLite most likely doesn't support this, because
It doesn't support stored procedures, and
It doesn't understand SQL Server T-SQL
SQL is actually a pseudo-standard. It differs between vendors and sometimes even between different versions of a product within the same vendor.
That said, I don't see any reason why you can't run any (SQLite compatible) SQL statement against the SQLite database by opening up connection and command objects, just like you would with SQL Server.
Since, however, you are new to databases and SQLite, here is how you should start. I assume you already have SQLite installed
Create a new Windows Application in Visual Studio 2008. The database application will be of no use to you.
Open the Server Explorer by pulling down the View menu and selecting Server Explorer.
Create a new connection by right-clicking on the Data Connections node in Server Explorer and clicking on Add New Connection...
Click the Change button
Select the SQLite provider
Give your database a file name.
Click OK.
A new Data Connection should appear in the Server Explorer. You can create your first table by right-clicking on the Tables node and selecting Add New Table.

Resources