Best practice SCRIPT Installation DataBase
I would like to have your opinions regarding best practices to adopt in SQL scripting to install a Data Base.
PROBLEM A) In my script I have several Batches to create Tables. Tables have many Foreign Keys to each others, at the moment I must arranges batches in the right order to avoid conflict with FK Tables. I would like to know if could be a good practice create Tables and all columns without FK first, and at the end of the script ALTER such tables adding FK.
PROBLEM B) My script should be use to create different DB on different Servers. Data Base could have different name on every installation. Now in my script I create a Database using:
CREATE DATABASE NameX
and:
USE NameX
to use it.
Because I would need update manually the script for every installation. I was thinking would be great to have a CENTRALIZED way for naming the Data Base inside a the script. In this way changing a simple variable would create the Data Base with my name and all USE statements. I tried to use LOCAL VARIABLES, but without success because after GO statements they go out of scope. I do not have any experience in using sqlcmd a开发者_运维知识库nd variables there.
Any idea how to solve it inside my script? PS: I use MS SQL 2008 and I will load my script in MS SMS
Thanks guys for your help, this community is great :-)
- avoid using "USE DATABASE"
- separate the database creating script and data object creating scripts
- use some code (Setup, Deploy) to execute creating database script by replacing @database_name with real name
alternative:
- use some replacement tool to prepare scripts before deploy (it just replace your @@@database_name@@@ with real name)
- use bat file to prepare scripts
alternative
- use Database Project in the Visual Studio. VS can generate some variables that setup projects can change in the deploy process..
Normally one starts with scripting all the tables, followed by the FK scripts, index scripts and the rest. This is normal practice, as you can't add relationships to tables that are not there...
As for your second problem - there is no way I am aware of for centralizing this. Your best option is a global search/replace of the database name on open files in SSMS.
精彩评论