我觉得我的商店有一个漏洞,因为我们没有一个可靠的过程来控制数据库模式更改的版本。我们做了很多备份,所以我们或多或少地得到了保护,但以这种方式依赖于最后一道防线是一种糟糕的做法。

令人惊讶的是,这似乎是一个共同的主线。与我交谈过的许多商店都忽略了这个问题,因为他们的数据库不会经常更改,他们基本上只是尽量做到一丝不苟。

不过,我知道这个故事是怎么发展的。这只是时间问题,迟早会出问题,会有东西丢失。

在这方面有什么最佳实践吗?你有哪些行之有效的策略?


数据库本身?没有

创建它们的脚本,包括静态数据插入、存储过程等;当然可以。它们是文本文件,它们包含在项目中,像其他东西一样签入和签出。

当然,在理想情况下,您的数据库管理工具可以做到这一点;但你必须遵守纪律。


我通过保存创建/更新脚本和生成sampledata的脚本来完成。


必须阅读将数据库置于版本控制之下。查看K. 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.


是的……我们的数据库是在ERwin中设计的,每个版本的ddl是自动生成的。ERwin文件保存在我们的源代码控制系统中(实际上,我们的工程文档也是如此)。


我非常喜欢Rails ActiveRecord迁移。它将DML抽象为ruby脚本,然后可以在源存储库中轻松地进行版本化。

然而,通过一些工作,您可以做到同样的事情。任何DDL更改(ALTER TABLE等)都可以存储在文本文件中。为文件名保留编号系统(或日期戳),并按顺序应用它们。

Rails在DB中还有一个'version'表,用于跟踪上一次应用的迁移。你可以很容易地做到这一点。


我们有一个每周的sql转储到一个颠覆回购。这是完全自动化的,但这是一项非常繁重的任务。

你会想要限制修改的数量,因为它真的会在一段时间后消耗磁盘空间!


是的,我们通过保留SQL作为构建的一部分来做到这一点——我们保留DROP。sql,创造。sql,用户。sql,值。SQL和版本控制,所以我们可以恢复到任何带标签的版本。

我们还有ant任务,可以在需要时重新创建db。

此外,SQL还被标记为与之配套的源代码。


是的,我认为版本化你的数据库是很重要的。当然不是数据,而是模式。

在Ruby On Rails中,这是由框架通过“迁移”来处理的。任何时候修改db,都需要编写一个脚本来应用更改并将其检入源代码控制。

我的团队非常喜欢这个想法,所以我们使用shell脚本和Ant将该功能添加到基于java的构建中。我们将该过程集成到部署例程中。在其他不支持DB版本开箱即用的框架中编写脚本来完成同样的事情是相当容易的。


我通过编写脚本输出所有对象(表定义、索引、存储过程等)来源控制数据库模式。但是,至于数据本身,只需依赖定期备份。这确保了所有的结构更改都被正确的修订历史记录捕获,但不会在每次数据更改时给数据库带来负担。


我所见过的最佳实践是创建一个构建脚本,在登台服务器上废弃并重新构建数据库。每次迭代都有一个用于数据库更改的文件夹,所有更改都用“Drop…创建“”。这样,您可以通过将构建指向您想要版本的文件夹,随时回滚到较早的版本。

我相信这是用NaNt/CruiseControl完成的。


我们使用复制和集群来管理数据库以及备份。我们使用Serena来管理SQL脚本和配置实现。在进行配置更改之前,我们将执行备份,作为更改管理流程的一部分。此备份满足我们的回滚需求。

我认为这完全取决于规模。您是在谈论需要离线备份和灾难恢复的企业应用程序吗?一个运行会计应用程序的小工作组?还是两者之间的任何地方?


我有一切必要的重新创建我的数据库从裸露的金属,减去数据本身。我相信有很多方法可以做到这一点,但我所有的脚本等都存储在subversion中,我们可以通过将所有这些从subversion中取出并运行安装程序来重建DB结构等。


是的。代码就是代码。我的经验法则是,我需要能够从头构建和部署应用程序,而不需要查看开发或生产机器。


在我们的业务中,我们使用数据库更改脚本。运行脚本时,它的名称存储在数据库中,并且不会再次运行,除非删除该行。脚本是基于日期、时间和代码分支命名的,因此可以控制执行。

在脚本在实际环境中运行之前,已经完成了大量的测试,所以一般来说,“oopsies”只发生在开发数据库上。


The most successful scheme I've ever used on a project has combined backups and differential SQL files. Basically we would take a backup of our db after every release and do an SQL dump so that we could create a blank schema from scratch if we needed to as well. Then anytime you needed to make a change to the DB you would add an alter scrip to the sql directory under version control. We would always prefix a sequence number or date to the file name so the first change would be something like 01_add_created_on_column.sql, and the next script would be 02_added_customers_index. Our CI machine would check for these and run them sequentially on a fresh copy of the db that had been restored from the backup.

我们还准备了一些脚本,开发人员可以用一个命令将本地db重新初始化到当前版本。


我们在源代码控制下有创建/修改脚本。至于数据库本身,当您有数百个表并且每分钟处理大量数据时,对所有数据库进行版本化将是CPU和HDD的杀手。这就是为什么在我看来,备份仍然是控制数据的最佳方式。


我们坚持使用变更脚本和主数据定义脚本。这些代码与任何其他源代码一起签入CVS。PL/SQL(我们是Oracle商店)在CVS中也是源代码控制的。变更脚本是可重复的,并且可以传递给团队中的每个人。基本上,仅仅因为它是一个数据库,就没有理由不对它进行编码并使用源代码控制系统来跟踪更改。


You should never just log in and start entering "ALTER TABLE" commands to change a production database. The project I'm on has database on every customer site, and so every change to the database is made in two places, a dump file that is used to create a new database on a new customer site, and an update file that is run on every update which checks your current database version number against the highest number in the file, and updates your database in place. So for instance, the last couple of updates:

if [ $VERSION \< '8.0.108' ] ; then
  psql -U cosuser $dbName << EOF8.0.108
    BEGIN TRANSACTION;
    --
    -- Remove foreign key that shouldn't have been there.
    -- PCR:35665
    --
    ALTER TABLE     migratorjobitems
    DROP CONSTRAINT migratorjobitems_destcmaid_fkey;
    -- 
    -- Increment the version
    UPDATE          sys_info
    SET             value = '8.0.108'
    WHERE           key = 'DB VERSION';
    END TRANSACTION;
EOF8.0.108
fi

if [ $VERSION \< '8.0.109' ] ; then
  psql -U cosuser $dbName << EOF8.0.109
    BEGIN TRANSACTION;
    --
    -- I missed a couple of cases when I changed the legacy playlist
    -- from reporting showplaylistidnum to playlistidnum
    --
    ALTER TABLE     featureidrequestkdcs
    DROP CONSTRAINT featureidrequestkdcs_cosfeatureid_fkey;
    ALTER TABLE     featureidrequestkdcs
    ADD CONSTRAINT  featureidrequestkdcs_cosfeatureid_fkey
    FOREIGN KEY     (cosfeatureid)
    REFERENCES      playlist(playlistidnum)
    ON DELETE       CASCADE;
    --
    ALTER TABLE     ticket_system_ids
    DROP CONSTRAINT ticket_system_ids_showplaylistidnum_fkey;
    ALTER TABLE     ticket_system_ids
    RENAME          showplaylistidnum
    TO              playlistidnum;
    ALTER TABLE     ticket_system_ids
    ADD CONSTRAINT  ticket_system_ids_playlistidnum_fkey
    FOREIGN KEY     (playlistidnum)
    REFERENCES      playlist(playlistidnum)
    ON DELETE       CASCADE;
    -- 
    -- Increment the version
    UPDATE          sys_info
    SET             value = '8.0.109'
    WHERE           key = 'DB VERSION';
    END TRANSACTION;
EOF8.0.109
fi

我相信有更好的方法来做到这一点,但到目前为止,它对我来说是有效的。


我通常为我所做的每一个更改构建一个SQL脚本,另一个用于恢复这些更改,并将这些脚本置于版本控制之下。

这样我们就可以根据需要创建一个新的最新数据库,并且可以轻松地在不同版本之间切换。每次我们发布版本时,我们都会把脚本放在一起(需要一些手工工作,但实际上很少困难),所以我们也有一组可以在版本之间转换的脚本。

是的,在你说之前,这与Rails和其他东西非常相似,但它似乎工作得很好,所以我毫不犹豫地承认我无耻地提出了这个想法:)


我们正在将所有数据库转移到源代码控制的过程中。我们使用sqlcompare脚本输出数据库(不幸的是,这是一个专业版的特性),并将结果放到SVN中。

实施的成功将在很大程度上取决于组织的文化和实践。这里的人相信为每个应用程序创建一个数据库。大多数应用程序都使用一组通用的数据库,这也导致了大量的数据库间依赖关系(其中一些是循环的)。由于我们的系统具有数据库间的依赖关系,将数据库模式放到源代码控制中是非常困难的。

祝你好运,你越早尝试,你的问题就会越早解决。


我们对所有dabase创建的对象进行源代码控制。为了让开发人员保持诚实(因为你可以在没有源代码控制的情况下创建对象),我们的dba定期寻找不在源代码控制中的任何东西,如果他们找到了什么,他们就会丢弃它,而不询问它是否ok。


我已经在http://dbdeploy.com/上使用了ThoughtWorks的dbdeploy工具。它鼓励使用迁移脚本。在每个版本中,我们将更改脚本合并到一个文件中,以简化理解,并允许dba“支持”更改。


我总是检查我的数据库结构转储到源代码控制。全数据库转储,但我通常只是压缩和存储。


我对创建脚本进行了版本控制,并在其中使用了svn版本标记。然后,每当我得到一个将要使用的版本时,我就在dbpatches/目录中创建一个脚本,命名为要上卷到的版本。该脚本的任务是在不破坏数据的情况下修改当前数据库。例如,Dbpatches /可能有名为201、220和240的文件。如果数据库当前处于201级别,则应用补丁220,然后再应用补丁240。

DROP TABLE IF EXISTS `meta`;
CREATE TABLE `meta` (
  `property` varchar(255),
  `value` varchar(255),
  PRIMARY KEY (`property`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `meta` VALUES ('version', '$Rev: 240 $');

在考虑一个好的补丁之前,不要忘记测试你的代码。购者自慎!


我们维护由ER工具(PowerAMC)生成的DDL(有时是DML)脚本。

我们有一个shell脚本工作台,它重命名以主干分支上的数字开头的脚本。 提交每个脚本并标记bugzilla编号。

这些脚本在需要时与应用程序代码合并到发布分支中。

我们有一个记录脚本及其状态的表。 在部署工具的每次安装中,每个脚本都按顺序执行,并记录在此表中。


我使用SQL CREATE脚本从MySQL workbench导出,然后使用他们的“导出SQL ALTER”功能,我最终得到了一系列创建脚本(当然编号)和ALTER脚本,可以应用它们之间的更改。

3.- Export SQL ALTER script Normally you would have to write the ALTER TABLE statements by hand now, reflecting your changes you made to the model. But you can be smart and let Workbench do the hard work for you. Simply select File -> Export -> Forward Engineer SQL ALTER Script… from the main menu. This will prompt you to specify the SQL CREATE file the current model should be compared to. Select the SQL CREATE script from step 1. The tool will then generate the ALTER TABLE script for you and you can execute this script against your database to bring it up to date. You can do this using the MySQL Query Browser or the mysql client.Voila! Your model and database have now been synchronized!

来源:MySQL Workbench Community Edition: Schema同步指南

当然,所有这些脚本都在版本控制下。


My team versions our database schema as C# classes with the rest of our code. We have a homegrown C# program (<500 lines of code) that reflects the classes and creates SQL commands to build, drop and update the database. After creating the database we run sqlmetal to generate a linq mapping, which is then compiled in another project that is used to generate test data. The whole things works really well because data access is checked at compile time. We like it because the schema is stored in a .cs file which is easy to track compare in trac/svn.


查看使用源代码控制管理数据库更改的LiquiBase。


这对我来说也一直是一个很大的烦恼——似乎对开发数据库进行快速更改,保存它(忘记保存更改脚本)太容易了,然后你就卡在那里了。您可以撤消刚才所做的并重新做它以创建更改脚本,当然,如果您愿意的话,也可以从头开始编写它,尽管这将花费大量的时间来编写脚本。

A tool that I have used in the past that has helped with this some is SQL Delta. It will show you the differences between two databases (SQL server/Oracle I believe) and generate all the change scripts necessary to migrate A->B. Another nice thing it does is show all the differences between database content between the production (or test) DB and your development DB. Since more and more apps store configuration and state that is crucial to their execution in database tables, it can be a real pain to have change scripts that remove, add, and alter the proper rows. SQL Delta shows the rows in the database just like they would look in a Diff tool - changed, added, deleted.

一个很好的工具。以下是链接: http://www.sqldelta.com/


是的,总是这样。您应该能够在需要时使用一组有用的示例数据重新创建生产数据库结构。如果你不这样做,随着时间的推移,保持运行的小改变会被遗忘,然后有一天你会被咬,严重的。这是一种保险,你可能认为你不需要,但当你这样做的那一天,它的价格是它的10倍!


RedGate软件提供了一些很棒的工具,可以帮助你对数据库进行版本化。确保让开发者为开发工作构建自己的独立本地数据库,而不是依赖于“开发服务器”,因为“开发服务器”有时可能停机,有时也可能不停机。


RedGate很棒,当数据库发生变化时,我们会生成新的快照(一个小的二进制文件),并将该文件作为资源保存在项目中。每当我们需要更新数据库时,我们使用RedGate的工具包来更新数据库,并且能够从空数据库创建新的数据库。

RedGate也制作数据快照,虽然我个人没有使用过,但它们同样强大。


仅供参考,几天前Dana也提出了这个问题…源代码控制中的存储过程/DB模式


我已经使用RedGate SQL Compare Pro与脚本文件夹进行模式同步,然后我将所有更新提交给版本控制。效果很好。


Your project team can have a DBA to whom every developer would forward their create alter, delete, insert/update (for master data) sql statements. DBAs would run those queries and on successfully making the required update would add those statements to a text file or a spreadsheet. Each addition can be labeled as a savepoint. Incase you revert back to a particular savepoint, just do a drop all and run the queries uptil the labelled savepoint. This approach is just a thought... a bit of fine tuning here would work for your development environment.


任何数据库接口代码都应该进入版本控制(存储过程、函数等)。

对于结构和数据,这是一个判断。我个人对我的数据库保持一个干净的结构模板,但由于它们的大小,不将它们存储在版本控制中。但是将它存储在版本控制中是非常有益的,即使对于只有历史记录也是如此。


A big problem, often overlooked, is that for larger web based systems, it is required to have a transitional period or bucket testing approach to making new releases. This makes it essential to have both rollback and a mechanism for supporting both the old and new schema in the same DB. This requires a scaffolding approach (made populist by the Agile DB folks). In this scenario, lack of process in DB source control can be a total disaster. You need old schema scripts, new schema scripts and a set of intermediate scripts, as well as a tidy up, once the system is fully on the new version (or rolled back).

需要的不是从头开始重新创建模式的脚本,而是一种基于状态的方法,在这种方法中,您只需要脚本将DB从一个版本移动到另一个版本,向前或向后移动到所需的状态。您的DB变成了一系列状态脚本,可以轻松地对其进行源代码控制,并与源代码的其余部分一起标记。


关于数据库模型本身有很多讨论,但是我们也将所需的数据保存在. sql文件中。

例如,为了让你的应用程序更有用,你可能需要在安装时这样做:

INSERT INTO Currency (CurrencyCode, CurrencyName) 
VALUES ('AUD', 'Australian Dollars');

INSERT INTO Currency (CurrencyCode, CurrencyName) 
VALUES ('USD', 'US Dollars');

我们会有一个名为currency的文件。subversion下的SQL。作为构建过程中的一个手动步骤,我们将比较以前的货币。SQL到最新版本,并编写升级脚本。


Visual Studio中的新数据库项目提供了源代码控制和更改脚本。

他们有一个很好的工具,可以比较数据库,并可以生成一个脚本,将一个数据库的模式转换为另一个数据库,或者更新一个数据库中的数据以匹配另一个数据库。

db模式被“分解”以创建许多许多小的.sql文件,每个DDL命令一个描述db。

+tom


附加信息2008-11-30

作为一名开发人员,我在过去的一年里一直在使用它,我真的很喜欢它。它可以很容易地比较我的开发工作和生产工作,并生成用于发布的脚本。我不知道它是否缺少dba在“企业级”项目中所需要的特性。

因为模式被“分解”到sql文件中,所以源代码控制可以正常工作。

One gotcha is that you need to have a different mindset when you use a db project. The tool has a "db project" in VS, which is just the sql, plus an automatically generated local database which has the schema and some other admin data -- but none of your application data, plus your local dev db that you use for app data dev work. You rarely are aware of the automatically generated db, but you have to know its there so you can leave it alone :). This special db is clearly recognizable because it has a Guid in its name,

VS DB项目在将其他团队成员所做的DB更改集成到您的本地项目/相关DB方面做得很好。但是您需要采取额外的步骤,将项目模式与本地dev db模式进行比较,并应用mods。这是有道理的,但一开始似乎很尴尬。

DB项目是一个非常强大的工具。它们不仅生成脚本,而且可以立即应用它们。请确保不要用它破坏您的生产数据库。;)

我真的很喜欢VS DB项目,我希望在我所有的DB项目中使用这个工具。

+tom


Here is a sample poor man's solution for a trigger implementing tracking of changes on db objects ( via DDL stateements ) on a sql server 2005 / 2008 database. I contains also a simple sample of how-to enforce the usage of required someValue xml tag in the source code for each sql command ran on the database + the tracking of the current db version and type ( dev , test , qa , fb , prod) One could extend it with additional required attributes such as , etc. The code is rather long - it creates the empty database + the needed tracking table structure + required db functions and the populating trigger all running under a [ga] schema.

USE [master]
GO

/****** Object:  Database [DBGA_DEV]    Script Date: 04/22/2009 13:22:01 ******/
CREATE DATABASE [DBGA_DEV] ON  PRIMARY 
( NAME = N'DBGA_DEV', FILENAME = N'D:\GENAPP\DATA\DBFILES\DBGA_DEV.mdf' , SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
 LOG ON 
( NAME = N'DBGA_DEV_log', FILENAME = N'D:\GENAPP\DATA\DBFILES\DBGA_DEV_log.ldf' , SIZE = 6208KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)
GO

ALTER DATABASE [DBGA_DEV] SET COMPATIBILITY_LEVEL = 100
GO

IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))
begin
EXEC [DBGA_DEV].[dbo].[sp_fulltext_database] @action = 'enable'
end
GO

ALTER DATABASE [DBGA_DEV] SET ANSI_NULL_DEFAULT OFF 
GO

ALTER DATABASE [DBGA_DEV] SET ANSI_NULLS OFF 
GO

ALTER DATABASE [DBGA_DEV] SET ANSI_PADDING ON 
GO

ALTER DATABASE [DBGA_DEV] SET ANSI_WARNINGS OFF 
GO

ALTER DATABASE [DBGA_DEV] SET ARITHABORT OFF 
GO

ALTER DATABASE [DBGA_DEV] SET AUTO_CLOSE OFF 
GO

ALTER DATABASE [DBGA_DEV] SET AUTO_CREATE_STATISTICS ON 
GO

ALTER DATABASE [DBGA_DEV] SET AUTO_SHRINK OFF 
GO

ALTER DATABASE [DBGA_DEV] SET AUTO_UPDATE_STATISTICS ON 
GO

ALTER DATABASE [DBGA_DEV] SET CURSOR_CLOSE_ON_COMMIT OFF 
GO

ALTER DATABASE [DBGA_DEV] SET CURSOR_DEFAULT  GLOBAL 
GO

ALTER DATABASE [DBGA_DEV] SET CONCAT_NULL_YIELDS_NULL OFF 
GO

ALTER DATABASE [DBGA_DEV] SET NUMERIC_ROUNDABORT OFF 
GO

ALTER DATABASE [DBGA_DEV] SET QUOTED_IDENTIFIER OFF 
GO

ALTER DATABASE [DBGA_DEV] SET RECURSIVE_TRIGGERS OFF 
GO

ALTER DATABASE [DBGA_DEV] SET  DISABLE_BROKER 
GO

ALTER DATABASE [DBGA_DEV] SET AUTO_UPDATE_STATISTICS_ASYNC OFF 
GO

ALTER DATABASE [DBGA_DEV] SET DATE_CORRELATION_OPTIMIZATION OFF 
GO

ALTER DATABASE [DBGA_DEV] SET TRUSTWORTHY OFF 
GO

ALTER DATABASE [DBGA_DEV] SET ALLOW_SNAPSHOT_ISOLATION OFF 
GO

ALTER DATABASE [DBGA_DEV] SET PARAMETERIZATION SIMPLE 
GO

ALTER DATABASE [DBGA_DEV] SET READ_COMMITTED_SNAPSHOT OFF 
GO

ALTER DATABASE [DBGA_DEV] SET HONOR_BROKER_PRIORITY OFF 
GO

ALTER DATABASE [DBGA_DEV] SET  READ_WRITE 
GO

ALTER DATABASE [DBGA_DEV] SET RECOVERY FULL 
GO

ALTER DATABASE [DBGA_DEV] SET  MULTI_USER 
GO

ALTER DATABASE [DBGA_DEV] SET PAGE_VERIFY CHECKSUM  
GO

ALTER DATABASE [DBGA_DEV] SET DB_CHAINING OFF 
GO

EXEC [DBGA_DEV].sys.sp_addextendedproperty @name=N'DbType', @value=N'DEV' 
GO

EXEC [DBGA_DEV].sys.sp_addextendedproperty @name=N'DbVersion', @value=N'0.0.1.20090414.1100' 
GO



USE [DBGA_DEV]
GO
/****** Object:  Schema [ga]    Script Date: 04/22/2009 13:21:29 ******/
CREATE SCHEMA [ga] AUTHORIZATION [dbo]
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Contains the objects of the Generic Application database' , @level0type=N'SCHEMA',@level0name=N'ga'
GO
/****** Object:  Table [ga].[tb_DataMeta_ObjChangeLog]    Script Date: 04/22/2009 13:21:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [ga].[tb_DataMeta_ObjChangeLog](
    [LogId] [int] IDENTITY(1,1) NOT NULL,
    [TimeStamp] [timestamp] NOT NULL,
    [DatabaseName] [varchar](256) NOT NULL,
    [SchemaName] [varchar](256) NOT NULL,
    [DbVersion] [varchar](20) NOT NULL,
    [DbType] [varchar](20) NOT NULL,
    [EventType] [varchar](50) NOT NULL,
    [ObjectName] [varchar](256) NOT NULL,
    [ObjectType] [varchar](25) NOT NULL,
    [Version] [varchar](50) NULL,
    [SqlCommand] [varchar](max) NOT NULL,
    [EventDate] [datetime] NOT NULL,
    [LoginName] [varchar](256) NOT NULL,
    [FirstName] [varchar](256) NULL,
    [LastName] [varchar](50) NULL,
    [ChangeDescription] [varchar](1000) NULL,
    [Description] [varchar](1000) NULL,
    [ObjVersion] [varchar](20) NOT NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'The database version as written in the extended prop of the database' , @level0type=N'SCHEMA',@level0name=N'ga', @level1type=N'TABLE',@level1name=N'tb_DataMeta_ObjChangeLog', @level2type=N'COLUMN',@level2name=N'DbVersion'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'dev , test , qa , fb or prod' , @level0type=N'SCHEMA',@level0name=N'ga', @level1type=N'TABLE',@level1name=N'tb_DataMeta_ObjChangeLog', @level2type=N'COLUMN',@level2name=N'DbType'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'The name of the object as it is registered in the sys.objects ' , @level0type=N'SCHEMA',@level0name=N'ga', @level1type=N'TABLE',@level1name=N'tb_DataMeta_ObjChangeLog', @level2type=N'COLUMN',@level2name=N'ObjectName'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'' , @level0type=N'SCHEMA',@level0name=N'ga', @level1type=N'TABLE',@level1name=N'tb_DataMeta_ObjChangeLog', @level2type=N'COLUMN',@level2name=N'Description'
GO
SET IDENTITY_INSERT [ga].[tb_DataMeta_ObjChangeLog] ON
INSERT [ga].[tb_DataMeta_ObjChangeLog] ([LogId], [DatabaseName], [SchemaName], [DbVersion], [DbType], [EventType], [ObjectName], [ObjectType], [Version], [SqlCommand], [EventDate], [LoginName], [FirstName], [LastName], [ChangeDescription], [Description], [ObjVersion]) VALUES (3, N'DBGA_DEV', N'en', N'0.0.1.20090414.1100', N'DEV', N'DROP_TABLE', N'tb_BL_Products', N'TABLE', N' some', N'<EVENT_INSTANCE><EventType>DROP_TABLE</EventType><PostTime>2009-04-22T11:03:11.880</PostTime><SPID>57</SPID><ServerName>YSG</ServerName><LoginName>ysg\yordgeor</LoginName><UserName>dbo</UserName><DatabaseName>DBGA_DEV</DatabaseName><SchemaName>en</SchemaName><ObjectName>tb_BL_Products</ObjectName><ObjectType>TABLE</ObjectType><TSQLCommand><SetOptions ANSI_NULLS="ON" ANSI_NULL_DEFAULT="ON" ANSI_PADDING="ON" QUOTED_IDENTIFIER="ON" ENCRYPTED="FALSE"/><CommandText>drop TABLE [en].[tb_BL_Products] --<Version> some</Version>&#x0D;
</CommandText></TSQLCommand></EVENT_INSTANCE>', CAST(0x00009BF300B6271C AS DateTime), N'ysg\yordgeor', N'Yordan', N'Georgiev', NULL, NULL, N'0.0.0')
INSERT [ga].[tb_DataMeta_ObjChangeLog] ([LogId], [DatabaseName], [SchemaName], [DbVersion], [DbType], [EventType], [ObjectName], [ObjectType], [Version], [SqlCommand], [EventDate], [LoginName], [FirstName], [LastName], [ChangeDescription], [Description], [ObjVersion]) VALUES (4, N'DBGA_DEV', N'en', N'0.0.1.20090414.1100', N'DEV', N'CREATE_TABLE', N'tb_BL_Products', N'TABLE', N' 2.2.2 ', N'<EVENT_INSTANCE><EventType>CREATE_TABLE</EventType><PostTime>2009-04-22T11:03:18.620</PostTime><SPID>57</SPID><ServerName>YSG</ServerName><LoginName>ysg\yordgeor</LoginName><UserName>dbo</UserName><DatabaseName>DBGA_DEV</DatabaseName><SchemaName>en</SchemaName><ObjectName>tb_BL_Products</ObjectName><ObjectType>TABLE</ObjectType><TSQLCommand><SetOptions ANSI_NULLS="ON" ANSI_NULL_DEFAULT="ON" ANSI_PADDING="ON" QUOTED_IDENTIFIER="ON" ENCRYPTED="FALSE"/><CommandText>CREATE TABLE [en].[tb_BL_Products](&#x0D;
    [ProducId] [int] NULL,&#x0D;
    [ProductName] [nchar](10) NULL,&#x0D;
    [ProductDescription] [varchar](5000) NULL&#x0D;
) ON [PRIMARY]&#x0D;
/*&#x0D;
<Version> 2.2.2 </Version>&#x0D;
&#x0D;
*/&#x0D;
</CommandText></TSQLCommand></EVENT_INSTANCE>', CAST(0x00009BF300B62F07 AS DateTime), N'ysg\yordgeor', N'Yordan', N'Georgiev', NULL, NULL, N'0.0.0')
INSERT [ga].[tb_DataMeta_ObjChangeLog] ([LogId], [DatabaseName], [SchemaName], [DbVersion], [DbType], [EventType], [ObjectName], [ObjectType], [Version], [SqlCommand], [EventDate], [LoginName], [FirstName], [LastName], [ChangeDescription], [Description], [ObjVersion]) VALUES (5, N'DBGA_DEV', N'en', N'0.0.1.20090414.1100', N'DEV', N'DROP_TABLE', N'tb_BL_Products', N'TABLE', N' 2.2.2 ', N'<EVENT_INSTANCE><EventType>DROP_TABLE</EventType><PostTime>2009-04-22T11:25:12.620</PostTime><SPID>57</SPID><ServerName>YSG</ServerName><LoginName>ysg\yordgeor</LoginName><UserName>dbo</UserName><DatabaseName>DBGA_DEV</DatabaseName><SchemaName>en</SchemaName><ObjectName>tb_BL_Products</ObjectName><ObjectType>TABLE</ObjectType><TSQLCommand><SetOptions ANSI_NULLS="ON" ANSI_NULL_DEFAULT="ON" ANSI_PADDING="ON" QUOTED_IDENTIFIER="ON" ENCRYPTED="FALSE"/><CommandText>drop TABLE [en].[tb_BL_Products] &#x0D;
</CommandText></TSQLCommand></EVENT_INSTANCE>', CAST(0x00009BF300BC32F1 AS DateTime), N'ysg\yordgeor', N'Yordan', N'Georgiev', NULL, NULL, N'0.0.0')
INSERT [ga].[tb_DataMeta_ObjChangeLog] ([LogId], [DatabaseName], [SchemaName], [DbVersion], [DbType], [EventType], [ObjectName], [ObjectType], [Version], [SqlCommand], [EventDate], [LoginName], [FirstName], [LastName], [ChangeDescription], [Description], [ObjVersion]) VALUES (6, N'DBGA_DEV', N'en', N'0.0.1.20090414.1100', N'DEV', N'CREATE_TABLE', N'tb_BL_Products', N'TABLE', N' 2.2.2 ', N'<EVENT_INSTANCE><EventType>CREATE_TABLE</EventType><PostTime>2009-04-22T11:25:19.053</PostTime><SPID>57</SPID><ServerName>YSG</ServerName><LoginName>ysg\yordgeor</LoginName><UserName>dbo</UserName><DatabaseName>DBGA_DEV</DatabaseName><SchemaName>en</SchemaName><ObjectName>tb_BL_Products</ObjectName><ObjectType>TABLE</ObjectType><TSQLCommand><SetOptions ANSI_NULLS="ON" ANSI_NULL_DEFAULT="ON" ANSI_PADDING="ON" QUOTED_IDENTIFIER="ON" ENCRYPTED="FALSE"/><CommandText>CREATE TABLE [en].[tb_BL_Products](&#x0D;
    [ProducId] [int] NULL,&#x0D;
    [ProductName] [nchar](10) NULL,&#x0D;
    [ProductDescription] [varchar](5000) NULL&#x0D;
) ON [PRIMARY]&#x0D;
/*&#x0D;
<Version> 2.2.2 </Version>&#x0D;
&#x0D;
*/&#x0D;
</CommandText></TSQLCommand></EVENT_INSTANCE>', CAST(0x00009BF300BC3A69 AS DateTime), N'ysg\yordgeor', N'Yordan', N'Georgiev', NULL, NULL, N'0.0.0')
SET IDENTITY_INSERT [ga].[tb_DataMeta_ObjChangeLog] OFF
/****** Object:  Table [ga].[tb_BLSec_LoginsForUsers]    Script Date: 04/22/2009 13:21:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [ga].[tb_BLSec_LoginsForUsers](
    [LoginsForUsersId] [int] IDENTITY(1,1) NOT NULL,
    [LoginName] [nvarchar](100) NOT NULL,
    [FirstName] [varchar](100) NOT NULL,
    [SecondName] [varchar](100) NULL,
    [LastName] [varchar](100) NOT NULL,
    [DomainName] [varchar](100) NOT NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
SET IDENTITY_INSERT [ga].[tb_BLSec_LoginsForUsers] ON
INSERT [ga].[tb_BLSec_LoginsForUsers] ([LoginsForUsersId], [LoginName], [FirstName], [SecondName], [LastName], [DomainName]) VALUES (1, N'ysg\yordgeor', N'Yordan', N'Stanchev', N'Georgiev', N'yordgeor')
SET IDENTITY_INSERT [ga].[tb_BLSec_LoginsForUsers] OFF
/****** Object:  Table [en].[tb_BL_Products]    Script Date: 04/22/2009 13:21:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [en].[tb_BL_Products](
    [ProducId] [int] NULL,
    [ProductName] [nchar](10) NULL,
    [ProductDescription] [varchar](5000) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
/****** Object:  StoredProcedure [ga].[procUtils_SqlCheatSheet]    Script Date: 04/22/2009 13:21:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [ga].[procUtils_SqlCheatSheet]                

as                 
set nocount on                 

--what was the name of the table with something like role                
/*                
SELECT * from sys.tables where [name] like '%POC%'                
*/                
-- what are the columns of this table                 
/*                
select column_name , DATA_TYPE , CHARACTER_MAXIMUM_LENGTH,  table_name  from Information_schema.columns where table_name='tbGui_ExecutePOC'                
*/                

-- find proc        
--what was the name of procedure with something like role                
/*                
select * from sys.procedures where [name] like '%ext%'                
exec sp_HelpText procName        
*/                
/*                
exec sp_helpText procUtils_InsertGenerator                
*/                
--how to list all databases in sql server                 
/*                
SELECT database_id AS ID, NULL AS ParentID, name AS Text FROM sys.databases ORDER BY [name]                
*/                

--HOW-TO LIST ALL TABLES IN A SQL SERVER 2005 DATABASE                
/*                
SELECT TABLE_NAME FROM [POC].INFORMATION_SCHEMA.TABLES                
WHERE TABLE_TYPE = 'BASE TABLE'                  
AND TABLE_NAME <> 'dtproperties'                  
ORDER BY TABLE_NAME                


*/                
--HOW-TO ENABLE XP_CMDSHELL START                
-------------------------------------------------------------------------                
-- configure verbose mode temporarily                 
-- EXECUTE sp_configure 'show advanced options', 1                 
-- RECONFIGURE WITH OVERRIDE                 
--GO                 


--ENABLE xp_cmdshell                 
-- EXECUTE sp_configure 'xp_cmdshell', '1'                 
-- RECONFIGURE WITH OVERRIDE                 
-- EXEC SP_CONFIGURE 'show advanced option', '1';                 
-- SHOW THE CONFIGURATION                 
-- EXEC SP_CONFIGURE;                 


--turn show advance options off                 
-- GO                 
--EXECUTE sp_configure 'show advanced options', 0                 
-- RECONFIGURE WITH OVERRIDE                 
-- GO                

--HOW-TO ENABLE XP_CMDSHELL END                
-------------------------------------------------------------------------                

--HOW-TO IMPLEMENT SLEEP                 
-- sleep for 10 seconds                 
-- WAITFOR DELAY '00:00:10' SELECT * FROM My_Table                

/* LIST ALL PRIMARY KEYS                 

SELECT                 
  INFORMATION_SCHEMA.TABLE_CONSTRAINTS.TABLE_NAME AS TABLE_NAME,                
  INFORMATION_SCHEMA.KEY_COLUMN_USAGE.COLUMN_NAME AS COLUMN_NAME,                 
  REPLACE(INFORMATION_SCHEMA.TABLE_CONSTRAINTS.CONSTRAINT_TYPE,' ', '_') AS CONSTRAINT_TYPE                 
FROM                 
  INFORMATION_SCHEMA.TABLE_CONSTRAINTS                 
  INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE ON                 
  INFORMATION_SCHEMA.TABLE_CONSTRAINTS.CONSTRAINT_NAME =                 
  INFORMATION_SCHEMA.KEY_COLUMN_USAGE.CONSTRAINT_NAME                 
WHERE                 
  INFORMATION_SCHEMA.TABLE_CONSTRAINTS.TABLE_NAME <> N'sysdiagrams'                 
ORDER BY                 
  INFORMATION_SCHEMA.TABLE_CONSTRAINTS.TABLE_NAME ASC                

*/                

--HOW-TO COPY TABLE AND THE WHOLE TABLE DATA , COPY TABLE FROM DB TO DB                
--==================================================START                 
/*                
use Poc_Dev                
go                
drop table tbGui_LinksVisibility                

use POc_test                
go                
select *                 
INTO [POC_Dev].[ga].[tbGui_LinksVisibility]                
from [POC_TEST].[ga].[tbGui_LinksVisibility]                


*/                
--HOW-TO COPY TABLE AND THE WHOLE TABLE DATA , COPY TABLE FROM DB TO DB                
--====================================================END                
--=================================================== SEE TABLE METADATA START                
/*                



SELECT c.name AS [COLUMN_NAME], sc.data_type AS [DATA_TYPE], [value] AS                 
[DESCRIPTION] , c.max_length as [MAX_LENGTH] , c.is_nullable AS [OPTIONAL]                 
, c.is_identity AS [IS_PRIMARY_KEY] FROM sys.extended_properties AS ep                 
INNER JOIN sys.tables AS t ON ep.major_id = t.object_id                 
INNER JOIN sys.columns AS c ON ep.major_id = c.object_id AND ep.minor_id                 
= c.column_id                 
INNER JOIN INFORMATION_SCHEMA.COLUMNS sc ON t.name = sc.table_name and                 
c.name = sc.column_name                 
WHERE class = 1 and t.name = 'tbGui_ExecutePOC' ORDER BY SC.DATA_TYPE                


*/                
--=================================================== SEE TABLE METADATA END               
    /*            
select * from Information_schema.columns                
select table_name , column_name from Information_schema.columns where table_name='tbGui_Wizards'                
    */            


--=================================================== LIST ALL TABLES AND THEIR DESCRIPTOINS START                
/*                

SELECT T.name AS TableName, CAST(Props.value AS varchar(1000)) AS                
TableDescription                
FROM sys.tables AS T LEFT OUTER JOIN                
(SELECT class, class_desc, major_id, minor_id,                
name, value                
FROM sys.extended_properties                
WHERE (minor_id = 0) AND (class = 1)) AS                
Props ON T.object_id = Props.major_id                
WHERE (T.type = 'U') AND (T.name <> N'sysdiagrams')                
ORDER BY TableName                
*/                
--=================================================== LIST ALL TABLES AND THEIR DESCRIPTOINS START                

--=================================================== LIST ALL OBJECTS FROM DB START                
/*                


use DB                
--HOW-TO LIST ALL PROCEDURE IN A DATABASE                
select s.name from sysobjects s where type = 'P'                
--HOW-TO LIST ALL TRIGGERS BY NAME IN A DATABASE                
select s.name from sysobjects s where type = 'TR'                
--HOW-TO LIST TABLES IN A DATABASE                 
select s.name from sysobjects s where type = 'U'                
--how-to list all system tables in a database                
select s.name from sysobjects s where type = 's'                
--how-to list all the views in a database                
select s.name from sysobjects s where type = 'v'                


*/                

/*                
Similarly you can find out other objects created by user, simple change type =                 

C = CHECK constraint                 

D = Default or DEFAULT constraint                 

F = FOREIGN KEY constraint                 

L = Log                 

FN = Scalar function                 

IF = In-lined table-function                 

P = Stored procedure                 

PK = PRIMARY KEY constraint (type is K)                 

RF = Replication filter stored procedure                

S = System table                 

TF = Table function                 

TR = Trigger                 

U = User table ( this is the one I discussed above in the example)                

UQ = UNIQUE constraint (type is K)                 

V = View                 

X = Extended stored procedure                
*/                



--=================================================== HOW-TO SEE ALL MY PERMISSIONS START                


/*                

SELECT * FROM fn_my_permissions(NULL, 'SERVER');                
USE poc_qa;                
SELECT * FROM fn_my_permissions (NULL, 'database');                
GO                

*/                
--=================================================== HOW-TO SEE ALL MY PERMISSIONS END                

/*               
--find table               

use poc_dev               
go               
select s.name from sysobjects s where type = 'u'  and s.name like '%Visibility%'              
select * from tbGui_LinksVisibility              

*/              

/* find cursor              

use poc      
go        
DECLARE @procName varchar(100)        
DECLARE @cursorProcNames CURSOR        
SET @cursorProcNames = CURSOR FOR        
select name from sys.procedures where modify_date > '2009-02-05 13:12:15.273' order by modify_date desc       

OPEN @cursorProcNames        
FETCH NEXT        
FROM @cursorProcNames INTO @procName        
WHILE @@FETCH_STATUS = 0        
BEGIN        

set nocount off;        
exec sp_HelpText @procName --- or print them        
-- print @procName        

FETCH NEXT        
FROM @cursorProcNames INTO @procName        
END        
CLOSE @cursorProcNames        

select @@error    

*/              


/* --  SEE STORED PROCEDURE EXT PROPS            

SELECT ep.name as 'EXT_PROP_NAME' , SP.NAME , [value] as 'DESCRIPTION' FROM sys.extended_properties as ep left join sys.procedures as sp on sp.object_id = ep.major_id where sp.type='P'            


-- what the hell I ve been doing lately on sql server 2005 / 2008
select o.name , 
(SELECT [definition] AS [text()] FROM sys.all_sql_modules where sys.all_sql_modules.object_id=a.object_id FOR XML PATH(''), TYPE) AS Statement_Text
, a.object_id, o.modify_date from sys.all_sql_modules a left join sys.objects o on a.object_id=o.object_id order by 4 desc



-- GET THE RIGHT LANG SCHEMA START 
DECLARE @template AS varchar(max)
SET @template = 'SELECT * FROM {object_name}'

DECLARE @object_name AS sysname

SELECT @object_name = QUOTENAME(s.name) + '.' + QUOTENAME(o.name)
FROM sys.objects o
INNER JOIN sys.schemas s
    ON s.schema_id = o.schema_id
WHERE o.object_id = OBJECT_ID(QUOTENAME(@LANG) + '.[TestingLanguagesInNameSpacesDelMe]')

IF @object_name IS NOT NULL
BEGIN
    DECLARE @sql AS varchar(max)
    SET @sql = REPLACE(@template, '{object_name}', @object_name)
    EXEC (@sql)
END
-- GET THE RIGHT LANG SCHEMA END 

--  SEE STORED PROCEDURE EXT PROPS end*/             
set nocount off
GO
EXEC sys.sp_addextendedproperty @name=N'AuthorName', @value=N'Yordan Georgiev' , @level0type=N'SCHEMA',@level0name=N'ga', @level1type=N'PROCEDURE',@level1name=N'procUtils_SqlCheatSheet'
GO
EXEC sys.sp_addextendedproperty @name=N'ProcDescription', @value=N'TODO:ADD HERE DESCRPIPTION' , @level0type=N'SCHEMA',@level0name=N'ga', @level1type=N'PROCEDURE',@level1name=N'procUtils_SqlCheatSheet'
GO
EXEC sys.sp_addextendedproperty @name=N'ProcVersion', @value=N'0.1.0.20090406.1317' , @level0type=N'SCHEMA',@level0name=N'ga', @level1type=N'PROCEDURE',@level1name=N'procUtils_SqlCheatSheet'
GO
/****** Object:  UserDefinedFunction [ga].[GetDbVersion]    Script Date: 04/22/2009 13:21:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [ga].[GetDbVersion]()
RETURNS VARCHAR(20)
    BEGIN
        RETURN convert(varchar(20) , (select value from sys.extended_properties where name='DbVersion' and class_desc='DATABASE') )
    END
GO
EXEC sys.sp_addextendedproperty @name=N'AuthorName', @value=N'Yordan Georgiev' , @level0type=N'SCHEMA',@level0name=N'ga', @level1type=N'FUNCTION',@level1name=N'GetDbVersion'
GO
EXEC sys.sp_addextendedproperty @name=N'ChangeDescription', @value=N'Initial creation' , @level0type=N'SCHEMA',@level0name=N'ga', @level1type=N'FUNCTION',@level1name=N'GetDbVersion'
GO
EXEC sys.sp_addextendedproperty @name=N'CreatedWhen', @value=N'getDate()' , @level0type=N'SCHEMA',@level0name=N'ga', @level1type=N'FUNCTION',@level1name=N'GetDbVersion'
GO
EXEC sys.sp_addextendedproperty @name=N'Description', @value=N'Gets the current version of the database ' , @level0type=N'SCHEMA',@level0name=N'ga', @level1type=N'FUNCTION',@level1name=N'GetDbVersion'
GO
/****** Object:  UserDefinedFunction [ga].[GetDbType]    Script Date: 04/22/2009 13:21:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [ga].[GetDbType]()
RETURNS VARCHAR(30)
    BEGIN
        RETURN convert(varchar(30) , (select value from sys.extended_properties where name='DbType' and class_desc='DATABASE') )
    END
GO
/****** Object:  Default [DF_tb_DataMeta_ObjChangeLog_DbVersion]    Script Date: 04/22/2009 13:21:40 ******/
ALTER TABLE [ga].[tb_DataMeta_ObjChangeLog] ADD  CONSTRAINT [DF_tb_DataMeta_ObjChangeLog_DbVersion]  DEFAULT ('select ga.GetDbVersion()') FOR [DbVersion]
GO
/****** Object:  Default [DF_tb_DataMeta_ObjChangeLog_EventDate]    Script Date: 04/22/2009 13:21:40 ******/
ALTER TABLE [ga].[tb_DataMeta_ObjChangeLog] ADD  CONSTRAINT [DF_tb_DataMeta_ObjChangeLog_EventDate]  DEFAULT (getdate()) FOR [EventDate]
GO
/****** Object:  Default [DF_tb_DataMeta_ObjChangeLog_ObjVersion]    Script Date: 04/22/2009 13:21:40 ******/
ALTER TABLE [ga].[tb_DataMeta_ObjChangeLog] ADD  CONSTRAINT [DF_tb_DataMeta_ObjChangeLog_ObjVersion]  DEFAULT ('0.0.0') FOR [ObjVersion]
GO
/****** Object:  DdlTrigger [trigMetaDoc_TraceDbChanges]    Script Date: 04/22/2009 13:21:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create trigger [trigMetaDoc_TraceDbChanges]
on database
for create_procedure, alter_procedure, drop_procedure,
create_table, alter_table, drop_table,
create_function, alter_function, drop_function , 
create_trigger , alter_trigger , drop_trigger 
as

set nocount on

declare @data xml
set @data = EVENTDATA()
declare @DbVersion varchar(20)
set @DbVersion =(select ga.GetDbVersion())
declare @DbType varchar(20)
set @DbType =(select ga.GetDbType())
declare @DbName varchar(256)
set @DbName =@data.value('(/EVENT_INSTANCE/DatabaseName)[1]', 'varchar(256)')
declare @EventType varchar(256)
set @EventType =@data.value('(/EVENT_INSTANCE/EventType)[1]', 'varchar(50)')
declare @ObjectName varchar(256)
set @ObjectName  = @data.value('(/EVENT_INSTANCE/ObjectName)[1]', 'varchar(256)')
declare @ObjectType varchar(25)
set @ObjectType = @data.value('(/EVENT_INSTANCE/ObjectType)[1]', 'varchar(25)')
declare @TSQLCommand varchar(max)
set @TSQLCommand = @data.value('(/EVENT_INSTANCE/TSQLCommand)[1]', 'varchar(max)')
declare @opentag varchar(4)
set @opentag= '&lt;'
declare @closetag varchar(4) 
set @closetag= '&gt;'
declare @newDataTxt varchar(max) 
set @newDataTxt= cast(@data as varchar(max))
set @newDataTxt = REPLACE ( REPLACE(@newDataTxt , @opentag , '<') , @closetag , '>')
-- print @newDataTxt
declare @newDataXml xml 
set @newDataXml = CONVERT ( xml , @newDataTxt)
declare @Version varchar(50)
set @Version = @newDataXml.value('(/EVENT_INSTANCE/TSQLCommand/CommandText/Version)[1]', 'varchar(50)')

-- if we are dropping take the version from the existing object 
if  ( SUBSTRING(@EventType , 0 , 5)) = 'DROP'
set @Version =( select top 1 [Version]  from ga.tb_DataMeta_ObjChangeLog where ObjectName=@ObjectName order by [LogId] desc)



declare @LoginName varchar(256) 
set @LoginName = @data.value('(/EVENT_INSTANCE/LoginName)[1]', 'varchar(256)')
declare @FirstName varchar(50)
set @FirstName= (select [FirstName] from [ga].[tb_BLSec_LoginsForUsers] where [LoginName] = @LoginName)
declare @LastName varchar(50)
set @LastName  = (select [LastName] from [ga].[tb_BLSec_LoginsForUsers] where [LoginName] = @LoginName)
declare @SchemaName sysname 
set @SchemaName = @data.value('(/EVENT_INSTANCE/SchemaName)[1]', 'sysname');
--declare @Description xml 
--set @Description = @data.query('(/EVENT_INSTANCE/TSQLCommand/text())')




--print 'VERSION IS ' + @Version
--print @newDataTxt
--print cast(@data as varchar(max))


-- select column_name from information_schema.columns where table_name ='tb_DataMeta_ObjChangeLog'
insert into [ga].[tb_DataMeta_ObjChangeLog]
(
[DatabaseName] ,
[SchemaName],
[DbVersion] ,
[DbType],
[EventType],
[ObjectName],
[ObjectType] ,
[Version],
[SqlCommand] ,
[LoginName] ,
[FirstName],
[LastName] 
)

values(

@DbName,
@SchemaName,
@DbVersion,
@DbType,
@EventType, 
@ObjectName, 
@ObjectType , 
@Version,
@newDataTxt, 
@LoginName , 
@FirstName , 
@LastName
)
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
DISABLE TRIGGER [trigMetaDoc_TraceDbChanges] ON DATABASE
GO
/****** Object:  DdlTrigger [trigMetaDoc_TraceDbChanges]    Script Date: 04/22/2009 13:21:29 ******/
Enable Trigger [trigMetaDoc_TraceDbChanges] ON Database
GO

是的,当然。每当有更改时,我们生成PostgreSQL模式的转储并签入。它已经救了我们很多次,而我才上任几个月。


我们对数据库周围的一切进行版本和源代码控制:

DDL(创建和更改) DML(参考数据、代码等) 数据模型更改(使用ERwin或ER/Studio) 数据库配置更改(权限、安全对象、常规配置更改)

我们使用Change Manager和一些自定义脚本来完成所有这些自动化作业。我们有变更管理器监视这些变更,并在变更完成时通知变更。


我使用SchemaBank来版本控制我所有的数据库模式更改:

从第一天开始,我将我的db模式转储导入其中 我开始用网络浏览器改变我的模式设计(因为它们是基于SaaS /云的) 当我想更新我的db服务器时,我从它生成更改(SQL)脚本并应用到db。在Schemabank中,它们要求我在生成更新脚本之前将工作提交为版本。我喜欢这种练习,这样当我需要的时候,我就可以随时追溯。

我们的团队规则是,在没有存储设计工作之前,永远不要直接接触db服务器。但它发生了,有人可能会被诱惑打破规则,为了方便。我们将再次将模式转储导入到模式银行中,并让它执行diff,如果发现不一致,则对某人进行攻击。虽然我们可以从它生成alter脚本,使我们的db和模式设计同步,但我们讨厌这样做。

顺便说一下,它们还允许我们在版本控制树中创建分支,这样我就可以维护一个用于登台,一个用于生产。还有一个用于编码沙盒。

一个非常整洁的基于web的模式设计工具,带有版本控制和变更管理。


Sadly, I've seen more than one team developing PL/SQL programs (stored procedures in Oracle) - sometimes ten thousands LOC - just by editing the code in TOAD (a database tool), without even saving the source to files (except for deployment). Even if the database is backuped regulary (wouldn't take that for granted, though), the only way to retrieve an old version of a stored procedure is to restore the whole database, which is many GB large. And of course sometimes concurrent changes in one file lead to loss of work, when more than one developer works on the same project.


“简短版本:将您的生产数据库转储到git存储库中,以实现即时备份解决方案。”


我相信每个DB都应该在源代码控制下,开发人员应该有一种简单的方法从头创建他们的本地数据库。受Visual Studio for Database Professionals的启发,我创建了一个开源工具,脚本MS SQL数据库,并提供了一种简单的方法将它们部署到您的本地DB引擎。试试http://dbsourcetools.codeplex.com/。玩得开心, -内森。


我使用ActiveRecord Migrations。这个Ruby gem可以在Rails项目之外使用,并且有适配器可以处理您遇到的大多数数据库。我的建议:如果你能够在Postgres上运行你的项目,你就会得到事务性的模式迁移。这意味着如果迁移只应用了一半,您不会最终得到一个损坏的数据库。


Kira的主要用例之一是通过显式地将数据库外部的模式指定为代码来进行数据库升级。然后,它可以管理数据库,并将其从任何版本升级到任何版本。


是的,我们的源代码控制我们的sql脚本也与subversion。这是一个很好的实践,您可以在需要时使用默认数据重新创建模式。


如果你的数据库是SQL Server,我们可能有你正在寻找的解决方案。SQL源代码控制1.0现在已经发布了。

http://www.red-gate.com/products/SQL_Source_Control/index.htm

它集成到SSMS中,并提供数据库对象和VCS之间的粘合剂。“脚本输出”是透明的(它在底层使用SQL比较引擎),这应该使它使用起来如此简单,以至于开发人员不会被阻止采用该过程。

一个可供选择的Visual Studio解决方案是ReadyRoll,它被实现为SSDT数据库项目的子类型。这采用了一种迁移驱动的方法,更适合DevOps团队的自动化需求。


我已经开始研究sqlHawk,它的目标是围绕这个问题提供(开源)工具。

它目前处于相当早期的阶段,但已经支持存储和执行存储过程以及运行脚本更新。

如果有任何人有时间看这个工具,我将非常感激。

为公然的自我推销道歉,但我希望这对某人有用!


对于oracle,我使用自己编写的java程序oracle-ddl2svn自动跟踪oracle DDL方案在SVN中的变化


I agree with many of the posting concerning ruby's ActiveRecord migrations - they are an elegant way to manage the database in small incremental files that everyone can share. With that said, I've recently implemented a project using VisualStudio's Database Project, and it's kinda made me a believer. Short story - you create a database project, import all (if any) existing database objects into it (tables/views/triggers/keys/users/etc). That import results in a "Create" script per object. To manage the database you alter the create script and then on deploy VS compares the target database to the state of the database residing in your project and apply the proper alter statements.

这真的有点神奇,我必须承认,这是VS团队做的更好的事情之一。到目前为止,我真的很感动。

当然,您可以在自己选择的版本控制系统中管理整个数据库项目。


作为一种规则,我们将所有的对象代码(存储过程、视图、触发器、函数等)都保存在源代码控制中,因为这些对象都是代码,而且几乎所有其他答案都同意,代码属于某种形式的版本控制系统。

As for CREATE, DROP, ALTER statements, etc. (DDL), we developed and use BuildMaster to manage the deployment of these scripts such that they can be run once and only once against a target database (whether they fail or not). The general idea is that developers will upload change scripts into the system and when it comes time for deployment, only the change scripts that haven't been run against the target environment's database will be run (this is managed very similarly to Autocracy's answer). The reason for this separation of script types lies in that once you manipulate a table's structure, add an index, etc., you effectively cannot undo that without writing a brand new script, or restoring the database - as opposed to the object code where you can simply drop a view or stored procedure then recreate it.

例如,当您将生产数据库恢复到集成环境中时,可以看到一些好处,系统会自动准确地知道哪些脚本没有运行,并将更改新恢复的数据库的表结构,使其与开发相关。


I've heard people say you absolutely have to keep your schemas in the database. I'm not sure I agree. This really depends on the system you're working with. If your system is relatively small and the data is not terribly important. And the the speed at which you need to bring another development environment online is crucial.. then yes.. you can benefit from it. However when your schema is useless without the data and the database is extremely large, it becomes virtually impossible to "source control" your database. Sure, you can still keep your DDL code in source control but that's essentially useless. You can't get the data needed without backup/restore.

在大型数据库开发工作中,我发现备份和恢复是首选的回滚选项。当然,你可以在源代码控制中保留过程、视图、函数等,但要保留表。SQL不是必需的。此外,如果您的部署过程是无懈可击的,那么您很可能永远不需要“回滚”您的生产环境。


虽然这个问题有很多很好的答案,但大多数答案都不包括市场上的创新变化,特别是商业工具。

下面是一个简短的数据库版本控制工具列表,我列出了每个工具的优缺点(完全披露:我为DBmaestro工作)

红门——已经上市很多年了。它使用集成了基于文件的版本控制的脚本来提供数据库对象的版本控制。

DBVS——使用集成了基于文件的版本控制的脚本来提供数据库对象的版本控制。

DBmaestro——在真实的数据库对象上提供版本控制过程(签出/签入)的强制执行。因此,版本控制存储库是否与应用程序使用的数据库同步是没有问题的。

我鼓励您阅读资深数据库专家Ben Taylor在LinkedIn https://www.linkedin.com/pulse/article/20140907002729-287832-solve-database-change-mangement-with-dbmaestro上发布的关于数据库强制变更管理解决方案的全面、公正的评论


要求开发团队使用SQL数据库源代码控制管理系统并不是防止问题发生的灵丹妙药。就其本身而言,数据库源代码控制引入了额外的开销,因为开发人员需要将他们对对象所做的更改保存在单独的SQL脚本中,打开源代码控制系统客户端,使用客户端签入SQL脚本文件,然后将更改应用到活动数据库。

我可以建议使用SSMS插件ApexSQL源代码控制。它允许开发人员通过向导直接从SSMS轻松地将数据库对象映射到源代码控制系统。该插件支持TFS、Git、Subversion和其他SC系统。它还包括对源控制静态数据的支持。

下载并安装ApexSQL源代码控制后,只需右键单击要进行版本控制的数据库,然后导航到SSMS中的ApexSQL源代码控制子菜单。单击Link database to source control选项,选择源代码控制系统和开发模型。之后,您需要为所选择的源代码控制系统提供登录信息和存储库字符串。

你可以阅读这篇文章了解更多信息:http://solutioncenter.apexsql.com/sql-source-control-reduce-database-development-time/


哇,这么多答案。对于可靠的数据库版本控制,您需要对更改数据库的代码进行版本控制。一些CMS提供配置管理工具,比如Drupal 8中的配置管理工具。以下是一个实用步骤的概述,可以安排您的工作流并确保数据库配置是版本化的,即使是在团队环境中: