Script for creating database if it doesn't exist yet in SQL Azure - sql

This question may related to Checking if database exists or not in SQL Azure.
In SQL Azure, I tried to use a script like this to check the existence of a database, and create the database if it doesn't exist yet (in both SQLCmd and SSMS):
IF db_id('databasename') IS NULL CREATE DATABASE databasename
GO
However, SQL Azure keeps telling me
Msg 40530, Level 16, State 1, Line 2
The CREATE DATABASE statement must be the only statement in the batch.
While the same script did work on a local SQL express instance.
Does this mean it is not supported on SQL Azure?
Or is there any work around?
Thanks in advance.
Eidt:
Let me clarify what I want to achieve:
I want a script which will create a certain database only if it doesn't exist before.
Is it possible to have such kind of script for SQL Azure?

We have a similar problem.
It looks like we can do something with SET NOEXEC ON, as in the following StackExchange answer.
IF (<condition>)
SET NOEXEC ON
ELSE
SET NOEXEC OFF
GO
CREATE DATABASE databasename
GO
SET NOEXEC OFF
GO

It's saying you can't do theck and create in the same piece of sql.
i.e you need to do Select IF db_id('databasename')
test the whether it returns null, and if so then execute the create database.

Related

SQL Server : update table tries to drop nonexistent triggers

I am using Microsoft SQL Server 2008 R2 (SP2). I am not using SQL Server Management Studio. I am using a simple webpage with a textarea for a query window that I built myself in PHP, so all I am doing are SQL commands -- no GUI stuff. Never had problems with it before, and I don't think the problems I'm having now are because of my PHP. Anyway, I would most appreciate answers in SQL code rather than answers that recommend I right-click the table name in Management Studio, if you get my drift.
Leading up to the problem...
I used to have three triggers on table dbo.MyOldTableName:
trgOldUpdate1, trgOldUpdate2, and trgOldInsert
I renamed the table using the following code:
EXEC sp_rename 'dbo.MyOldTableName', 'MyNewTableName';
I then dropped those three old triggers and created the following three new triggers (which do the same thing but point to the new table and have new names):
trgNewUpdate1, trgNewUpdate2, and trgNewInsert
I ran this SQL and saw only the new triggers:
SELECT
referencing_schema_name,
referencing_entity_name,
referencing_id,
referencing_class_desc,
is_caller_dependent
FROM
sys.dm_sql_referencing_entities ('dbo.MyOldTableName', 'OBJECT');
I ran this SQL and the old triggers are not there:
SELECT * FROM sys.triggers;
Now all of that above information is simply background. Here is the actual problem. I ran a simple update command (like this SQL):
UPDATE [dbo].[MyNewTableName] SET ColumnName = ColumnName;
...and got these error messages:
Cannot drop the trigger 'dbo.trgOldUpdate2', because it does not exist or you do not have permission.
Cannot drop the trigger 'dbo.trgOldUpdate1', because it does not exist or you do not have permission.
Cannot drop the trigger 'dbo.trgOldUpdate1', because it does not exist or you do not have permission.
Cannot drop the trigger 'dbo.trgOldUpdate2', because it does not exist or you do not have permission.
First, why is SQL Server trying to drop triggers on a simple update command (And before you ask, no, the trigger code itself never drops anything at all)?
Second, why is SQL Server looking for triggers that don't exist?
Third and most important, how do I stop this from happening?
Many thanks in advance for your clear, concise, and self-contained answers! (Hey, a guy can dream, can't he?)
My guess is that there was an error in the trigger DROP/CREATE script such that the DROP statements of the old triggers were inadvertently included in in one of the update triggers. Check the new triggers to see if that is the case:
EXEC sp_helptext N'trgNewUpdate1';
EXEC sp_helptext N'trgNewUpdate2';

sql server trigger to update another database whenever a sproc is created

Is there a way to update another database with the newly created stored procedure whenever a stored procedure is created in the main database?
For example, i have two databases, DB1 and DB2.
When I create a stored procedure in DB1, i want that same procedure to created in DB2 automatically? Is there a trigger that can do this?
USE [DB1]
CREATE PROCEDURE [dbo].[TestSproc]
..something
AS
BEGIN
...something
END
I know a use [DB2] statement will do the job, but i want this to be done automatically. Any thought?
Thanks for the help!
This might be a bit evil, but in SQL Server you are able to create DDL triggers which fire when you create/alter/drop tables/procedures etc. The syntax to fire when a procedure is created is:
CREATE TRIGGER <proc-name>
ON DATABASE
FOR CREATE_PROCEDURE
AS
--Your code goes here
In a DDL trigger you get access to an object called EVENTDATA. So to get the text of the procedure you created:
SELECT EVENTDATA().value('(/EVENT_INSTANCE/TSQLCommand/CommandText)[1]','nvarchar(max)')
Now all you need to do is keep that value and execute it in your secondary database. So your query becomes something like this, though I leave the code to update the secondary database down to you as I don't know if it's on the same server, linked server etc.:
CREATE TRIGGER sproc_copy
ON DATABASE
FOR CREATE_PROCEDURE
AS
DECLARE #procedureDDL AS NVARCHAR(MAX) = EVENTDATA().value('(/EVENT_INSTANCE/TSQLCommand/CommandText)[1]','nvarchar(max)')
--Do something with #procedureDDL
As this is not tested, there's probably a few gotchas. For example, what happens if you create procedure with full name (CREATE PROC server.database.schema.proc)
No simple solution for this unless you want to execute the same statement twice, once on each target database,
One thing that comes to my mind is that you can Set up Replication and only publish Stored Procedures to your second database which will be the subscriber in this case.
Following is the window where you select which Objects you want to send over to your secondary databases.

Alter All Triggers via T-SQL

Is there a way to update/alter all triggers using Looping T-SQL or a C# Code ?. I need it too update all the triggers in my database because the RAISERROR command has changed in sql server 2012.
You can script out all the triggers into a text file. See:
How to Generate Scripts For All Triggers in Database Using Microsoft SQL Server Management Studio
Then, you can use a text editor to replace the code you need to replace. Then, you can drop your triggers and recreate them. I don't know if your referring to a production database, or one that you are doing development on. I am assuming from your question that you are prepared to make these major changes to your database. Make sure you back up your database first, in any event.
You can get all trigger using
SELECT [name] FROM [sys].[triggers]
and loop through each trigger and execute
EXEC sp_helptext 'TriggerName'
so you will have the create statement with it...

Problem with SQL Server client DB upgrade script

SQL Server 2005, Win7, VS2008. I have to upgrade database from the old version of product to the newer one. I'd like to have one script that creates new database and upgrades old database to the new state. I am trying to do the following (SQL script below) and get the error (when running on machine with no database ):
Database 'MyDatabase' does not exist. Make sure that the name is
entered correctly.
The question is:
How can I specify database name in upgrade part
Is the better way to write create/upgrade exists ?
SQL code:
USE [master]
-- DB upgrade part
if exists (select name from sysdatabases where name = 'MyDatabase')
BEGIN
IF (<Some checks that DB is new>)
BEGIN
raiserror('MyDatabase database already exists and no upgrade required', 20, -1) with log
END
ELSE
BEGIN
USE [MyDatabase]
-- create some new tables
-- alter existing tables
raiserror('MyDatabase database upgraded successfully', 20, -1) with log
END
END
-- DB creating part
CREATE DATABASE [MyDatabase];
-- create new tables
You don't usually want to explicitly specify database name in a script. Rather, supply it exernally or pre-process the SQL to replace a $$DATABASENAME$$ token with the name of an actual database.
You're not going to be able to include the USE [MyDatabase] in your script since, if the database doesn't exist, the query won't parse.
Instead, what you can do is keep 2 separate scripts, one for an upgrade and one for a new database. Then you can call the scripts within the IF branches through xp_cmdshell and dynamic SQL. The following link has some examples that you can follow:
http://abhijitmore.wordpress.com/2011/06/21/how-to-execute-sql-using-t-sql/
PowerShell may make this task easier as well, but I don't have any direct experience using it.

Simulate a table creation with SQL

Is there a standard way to simulate a table creation in a database by using SQL? I don't want the table to be created, just check if it could be created.
One way would be to create it and then delete it again.
Any other way?
Most major servers support transactional DDL, so you can do something along these lines:
begin transaction
create table Foo ...
rollback transaction
Theoretically, in case of error it should be reported back to client, but table will not be created altogether.
Depends on the SQL DBMS you're interested in. For example Postgres supports transactional DDL and the following will work:
START TRANSACTION;
CREATE TABLE ... ();
<check for error here>
ROLLBACK;
If you're using MySQL, you could create it using a transient storage engine, like MEMORY .
Really, you have to actually create it to make sure everything is OK.
Foreign key references, functions used as default or check constraints or in computed columns are not checked until execute time.
One basic method (SQL Server) is to use "SET FMTONLY ON".
Useful for checking the statement is valid, though won't tell you everything (e.g. if the table already exists).
This will succeed:
SET FMTONLY ON
EXECUTE ('CREATE TABLE SomeTable(SomeField INTEGER)')
SET FMTONLY OFF
This will not:
SET FMTONLY ON
EXECUTE ('CREATE TABLE SomeTable(dodgysyntax)')
SET FMTONLY OFF
This approach is probably more useful for SELECT statements, which is what I've used it for in the past. It doesn't actually execute the statement, but returns out the metadata.