SQL: programmatically copy stored procedures from one db to another - sql

I'm looking for a way to copy stored procedures from one sql database to another on the same instance. It needs to be automatic, preferably through code (t-sql or anything), so using the generate scripts trick is not viable (plus I don't want to maintain that many scripts, and people forget to run them).
I've searched a bit on this and have not found a workable solution. Someone suggested a clever trick with generating all the stored procedure text into a sql field and then converting that and executing it on the destination db but unfortunately that had issues.
Has anyone got any other ideas on how this can be done, if it's at all possible?
If I can't do it programmatically, would there be a quick solution using ssis?
Thanks.
Edit: Using mixture of sql 2005 and 2008 versions.

You can do it programatically in .NET using the SMO framework.
Free/easy implementation could be done via PowerShell.
I have a script that does just this - it generates the scripts for SQL objects, including Stored Procs, and executes the creation scripts on the target server.
It's a handy workaround when security concerns don't allow linked servers but you need to keep certain resources in sync across multiple servers.
If all you care about are the procs, it should be fairly straightforward to check sys.sql_modules on your source and target DBs and execute any that don't exist in the target via the definition field in that view.

Related

Stored Procedure to generate insert and create SQL for database

How can I move a db from one server to another (I only have access to the database with mylittleadmin). Like the title says, I guess the "easiest" way would be by generating SQL with a stored procedure.
I'm using SQL Server 2008 on both servers.
In the codeplex project Extreme T-SQL Script I have written T-SQL procedures to script the content of tables. I just abandoned its use myself in favor of ssms tools pack, but the later is no option for you.
When using these procedures in SSMS or VS the main problem is that Microsoft has limits on max column width and max length of output from Print-Statements.
I can't predict, which such limits exist when using mylittleadmin.
It depends on which datatypes and which varchar length you are using. Writing scripts that handle special needs is possible.
Further you need something to script the database objects first and it might be difficult to find something for that, as most people just use SSMS for this purpose. sp_helptext might help to script procedures.
In SSMS, you have the ability to copy or move a database from one instance of SQL Server to another. You can right-click on the database in SSMS, choose Tasks and then Copy Database...
Or, of course, you can simply backup the DB and restore on your target server.
(I have no idea what 'myLitleAdmin' is that you referred to)
You dont need to make a stored procedure. The easiest way to do it is by right click on your database -->task-->back up and create a backup.
after that you can restore your database on the other server.
If you have a license for myLittleAdmin then do as their web states. It says
"Purchasing a license gives you unlimited mail support.
Send your request at support#mylittletools.net"
Actually I found out that you could make a backup of the database in myLittleAdmin. The resulting .bak file was then emailed to me as a link.
Thanks for the comments though, voted up some of them :)

SQL SERVER Project

My Application Database Without Project and without Source safe, i planned to make my DB to be as project and add it to TFS, but I have no idea how to script the stored procedures, Triggers, Views, Functions, and what is the best practice to Make Update Script for All My stored procedures, Triggers, Views, and Functions to My customers DB.
The best procedure (IMHO) is to manually maintain a strict version of your schemas. Then when you need to make changes you write a delta script to move from one version to the next. I suggest you write the DDL scripts by hand -- you can make them concise and comment them.
You can use a tool like Visual Studio Team System for database architects, take a look at Running static code analysis on SQL Server database with Visual Studio Team System for database architects it will show you how to import the data, disregard the static code analysis that comes later it does not apply to your question
I've found a good way to get SQL scripts into SCM from an existing database is to use SMSS's "export all to script" option or whatever it's called, can't remember now.
Then every other change you add the change script into your SCM with a different version number in the file name.
Every release (or set cycle depending on your development/release methodology) you apply all change scripts, then re-script the entire database, tag it, and start again.
The best way to do it - save the database in TFS as set of database creation script, i.e. MyTable table should be added to TFS as MyTable.sql file (CREATE TABLE...) etc. We are using SQL Examiner to do this - see the following article: How to keep your database under version control
We are working with SVN and I never tested SQL Examiner with TFS, but I know that the tool supports TFS.

Find SQL objects missing from source control

We use Source Safe and are migrating to Source Gear. We know that we have sql objects (procs, triggers, views, functions) that are in sql but were never added to the source code repository. What is the best way to hunt those down so I can add them?
Create an empty database and execute all SourceSafe scripts on it.
Then run Sql Compare to see what's missing.
There's an early access release of SQL Source Control, which links your database in SSMS to SourceGear Vault. This could make source controlling your database easier going forward, http://www.red-gate.com/messageboard/viewtopic.php?t=12265.

Should you store your SQL Stored Procedures in Source Control?

When developing an application with lots of stored procedures, should you store them in some sort of source versioning system (such as source-safe, TFS, SVN)? If so, why? And is there a convenient front end way to do this with SQL Server Management Studio?
Yes. All code should be stored in source control.
Simply put, code is code and mistakes happen. It's nice to be able to go back and see what changed over time and be able to go back to those changes.
We have to add it manually to a source control system, but you can create addons for the Sql Server the Management System. I haven't ever created one to automatically add it to source control, but I suppose you could. Also, all the code is stored in sql tables, so you could in theory create a process or something to go through the table(s) and retrieve all the code and commit it automatically.
Update: I would always write extra code to check and see if the code exists and if it doesn't create a filler procedure and then the actual script do and alter procedure.
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE
id = OBJECT_ID(N'[dbo].[SomeStoredProcedure]') AND
OBJECTPROPERTY(id,N'IsProcedure') = 1)
EXEC sp_executesql N'CREATE PROCEDURE [dbo].[SomeStoredProcedure] AS
SELECT ''SPROC Template'''
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE SomeStoredProcedure
Doing a drop and recreate will remove all the user permissions you have setup for it.
ABSOLUTELY POSITIVELY WITHOUT QUESTION NO EXCEPTIONS IN ALL PERPETUITY THROUGHOUT THE UNIVERSE YES!
Get your database under version control. Check the series of posts by Scott Allen.
When it comes to version control, the database is often a second or even third-class citizen. From what I've seen, teams that would never think of writing code without version control in a million years-- and rightly so-- can somehow be completely oblivious to the need for version control around the critical databases their applications rely on. I don't know how you can call yourself a software engineer and maintain a straight face when your database isn't under exactly the same rigorous level of source control as the rest of your code. Don't let this happen to you. Get your database under version control.
I recommend that you do store them. You never know when you'll need to rollback, or dig into logic you may have removed..
Here's a good way to easily grab your Stored Procs into files that you can throw into whatever source control you desire..
Stored Procedures to .sql files
Storing stored procedures is a great idea. Its a pain though. Just how do you get all that stuff into subversion? You can manually do it, but then its tedious and you end up not doing it at all.
I use a tool from the subsonic project.
sonic.exe version /server servername /db databasename /out outputdirectory
This command saves everything to 2 text files. One contains database schema, stored procs, user accounts, constraints, and primary keys. The other one contains the data.
Now that you have these two files you can use subversion(cvs,source safe) to move it into source control.
More info for using The Command Line Tool (SubCommander)
Most definitely yes. Then the question becomes how you store them in source control. Do you drop and recreate the stored procedure or just alter, do you add permissions at the end of the script or in a separate script. There was a post on Coding Horror a while back about the topic that I found interesting. Is Your Database Under Version Control?
Sure you should.
In MS SQL 2008, you can do it right from Management Studio.
SQL is code. All code belongs under source code control.
That is all.
Absolutely.
Positively.
A set of SPs is an interface, that is likely to be modified more frequently than structural changes.
And because SPs contain business logic, changes should be stored in version control to track the modifications and adjustments to the logic.
Storing these in version control is a symptom of organizational maturity at a coding level, and is a best practice.
Most definitely.
You should.
To my knowledge, no such tool exists to automate this process. At least, five years ago, when I was considering building one, there didn't seem to be any competition.
We store our procs in Subversion, all your SQL Code including DDL should be in some kind of source control repository
SPs and table schemas for that matter are all assets that should be under version control. In a perfect world the DB would be built from scripts, including the test data, as part of your CI process. Even if that's not the case, having a DB/developer is a good model to follow. In that way new ideas can be tried out in a local sandbox without impacting everyone, once the change is tested it can be checked in.
Management Studio can be linked to source control, although I don't have experience of doing this. We've always tracked our SP/schema as files. Management studio can automatically generate change scripts, which are very useful, as table drop/recreate can be too heavy handed for any table that has data.
SQL procs also surely need the same security/benefits of version control as the rest of the code in the project.
As others have said, yes they should be.
I don't know of an easy way to do this with SQL Server Management Studio, but if you also use Visual Studio, database projects are a great way to manage this.
There are methods in SMO to generate scripts if you prefer to code your own scripting tool.
http://www.sqlteam.com/article/scripting-database-objects-using-smo-updated
If you're not using asset management alongside source control, then I say throw everything in source control. Images, word documents, the whole shebang. Can't lose it, can always reverse any changes to it and if any machine goes down - nothing is lost.

Best way to version control T-SQL? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Stored procedures/DB schema in source control
What's the best way to version control my tables, views, sprocs, etc? Preferably automated or at least semi-automated :)
Thanks
I asked this one yesterday and got some nice responses:
Stored procedures/DB schema in source control
The articles from K Scott Allen say it all:
http://odetocode.com/Blogs/scott/archive/2008/01/31/11710.aspx
Write migration scripts for all db changes and keep them in a repository. Enforce a policy of making all changes to the db only by running a script; that way there is a record of what has been done, and a way to revert it. Investigate whether there's a migrations framework available for your favorite language/db combination.
I use Visual Studio 2008 Pro create Database projects (Other project types -> Database). We already use SVN as a code repository, so a project with a bunch of .sql files representing your stored procedures is just another thing to put in the repository - you can see diffs/history etc. This works the same with VSS or any other repository you use.
The nice thing about Database projects is that your project will remember your connection string, and all you have to do is right click on a .sql file (or select all of them at once!) and select run to update it in the db. This makes it easy to update your .sql files from the repository and run them all to update all your stored procedures, verifying your database is updated in seconds.
You can also select create a LINQ project (Visual C# -> Database) and store all your LINQ code in your repository.
Hope that helps!
If you were super lazy you could use the SMO (SQL Server Management Objects) or if using SQL Server prior to 2005 the DMO (distributed managmeent objects) to script out all tables/views/stored procedures daily and then compare the script to the script in source control and if there are any changes check the new version in. You won't be able to necessarily have as pretty of a script as if you just created all db changes in scripts, but at least you can recreate all tables/stored procedures/views. For example, in my table creation scripts there are often comments.
Here is an article to get you started on scripting: http://www.sqlteam.com/article/scripting-database-objects-using-smo-updated.
Again, this is mainly if you are too lazy to bother with version control and it won't help if you change something twice in one day. Also any data migration scripts still have to be saved and checked in because this won't pick up ad hoc SQL, only database objects.
I have written a DDL trigger which logs all the changes done to the definition of SQL objects (triggers, tables, SP, view etc). I could very well invoke extended SP from the trigger and store the details in another Database and use that as repository.
But if your team is really disciplined any source control should do the trick. The trigger is used as an audit mechanism and it's ideal for teams which are geographically scattered.
Try Randolph, One of the best SQL Version control tools I know.
I'm using Visual Studio Database edition which can export the schema from SQL Server in to a Visual Studio project. This is then stored in Source Control and can be deployed where ever needed. The VS Database project is just a bunch of scripts though and it's a clunky way of working.
A more robust method would be to use a database migration framework and if you're working with .Net check out this blog post for a good description http://flux88.com/NETDatabaseMigrationToolRoundup.aspx.
Update
As mentioned in the comments, this page is no more. So here is the last known snapshot from wayback machine http://web.archive.org/web/20080828232742/http://flux88.com/NETDatabaseMigrationToolRoundup.aspx