SQL - create database and tables in one script - sql

Sorry if already asked, but I can't find anything on this.
I am moving something over from MySQL to SQL Server I want to have a .sql file create a database and tables within the database. After working out syntax kinks I have gotten the files to work (almost).
If I run
IF db_id('dbname') IS NULL
CREATE DATABASE dbname
it works fine, and if I run
CREATE TABLE dbname.dbo.TABLE1 (
);
...
CREATE TABLE dbname.dbo.TABLEN (
);
it also works fine. But, if I run them in the same file I get this error
Database 'dbname' does not exist
Right now, the CREATE TABLE statements are not within the IF statement, which I would like, but I also cannot seem to find the syntax for that. ( { } does not work?)
So my big question is, how do I ensure a particular command in a .sql file is completed before another in SQL Server?
My second question is, how do I include multiple instructions within an IF clause?
To be clear, I have been running this into sqlcmd.

Put a GO command between queries.
IF db_id('dbname') IS NULL
CREATE DATABASE dbname
GO
CREATE TABLE dbname.dbo.TABLE1 (
);
CREATE TABLE dbname.dbo.TABLEN (
);
As for putting the table statements in the IF, you wouldn't be able to because of the GO command. You could create additional IF statements afterwards, to check for each tables pre-existence.
The syntax for a block if is:
IF condition
BEGIN
....
....
END

Between creating the database and creating the tables you will need a USE statement.
USE dbname
This way the tables will be created in the correct place, without having to specify the DB name on everything.
Also, GO and BEGIN...END like everyone else is saying.

You have to separate the statements with the GO keyword:
sql query
GO
another sql query
GO
and so on

By placing a GO between statements (to create separate batches of statements)

Related

How to get CREATE TABLE Statement from existing table in db2?

I am using DB2 and Oracle SQL Developer.
How to get the CREATE TABLE Statements from the existing tables?
There are too many tables and it will be a very lengthy process to do manually.
There is a special db2look utility for DDL extraction in Db2. You may refer to its options and their meaning at this link.
If you want SQL access to its capabilities, you may use the SYSPROC.DB2LK_GENERATE_DDL stored procedure supporting most of the utility's options. The routine has an output parameter getting "invocation number" int value after its call.
In case of a single table:
CALL SYSPROC.DB2LK_GENERATE_DDL ('-e -noview -t MY_SCHEMA.MY_TABLE', ?);
SELECT SQL_STMT
FROM SYSTOOLS.DB2LOOK_INFO_V
WHERE OP_TOKEN = <value_of_output_parameter_from_call_above>
ORDER BY OP_SEQUENCE;
In SQLDeveloper if you can see the table there's the initial Create Table Statement in the SQL Tab
You should do that for each table, this is a way to do it but I'm not sure it's fast enough for you.

SQL script syntax for multiple databases under one user

This is probably stupid simple, but for some reason I'm having trouble getting it to work. I have a typical import script I'm trying to run on a MS SQL server with one master user (as opposed to a single user with only access to one database).
When I run the .SQL script, it creates the database and then starts to create tables. Here's where it gets interesting. It's not creating the databases under the DB I just made. It's throwing the tables under the "System Databases" view and not restricting the table creation to the DB that was just created.
I have tried:
CREATE TABLE table_name
CREATE TABLE database_name.table_name
Maybe I'm overlooking something really easy. I don't usually run into this with MySQL with a single user mapped to one database, I think since the user can only see that one database, so MySQL assumes it must be the one to work with.
The difference now is that I'm using MSSQL 2008 and maybe it works a little differently and I'm overlooking something. Thanks for your help!
Tried this too. No luck. Says database doesn't exist when it tries to create the table. I would think being a top/down read of the query script it would first create the database, then try to create the table afterwards.
CREATE DATABASE DATABASENAME;
CREATE TABLE DATABASENAME.dbo.TABLENAME
(
field_one VARCHAR(100) NOT NULL,
field_two INT NOT NULL,
PRIMARY KEY(field_one)
)
This is a working example after getting it all figured out. This syntax works well and I don't need to specify the DBO pathing stuff before table names this way. Cleaner and got me the results I was looking for. Thanks everyone.
IF Db_id('DBNAME') IS NULL
CREATE DATABASE DBNAME;
GO
USE [DBNAME];
GO
CREATE TABLE TABLENAME
(
COL1 VARCHAR(100) NOT NULL,
COL2 INT NOT NULL,
PRIMARY KEY(COL2)
)
INSERT INTO TABLENAME
(COL1,
COL2)
VALUES('1234',1001),
('1234',1002),
('1234',1003),
('1234',1004)
It basically just does a check to make sure database is created before doing anything else, then sets the USE database to the one I'm working with. Everything else is just normal SQL, so have fun. Cheers!
Probably you need to include the USE sentence at the begining of your script in order to indicate the database as follows:
USE [database_name]
GO
By default SQL-SERVER use the master DB that´s listed under system databases.
Other way is to use the database prefix, but including the owner:
INSERT INTO database_name.dbo.table_name
INSERT INTO database_name..table_name

Creating table in mysql

Is it possible to create more than one table at a time using single create table statement.
For MySQL, you can use multi-query to execute multiple SQL statements in a single call. You'd issue two CREATE TABLE statements separated by a semicolon.
But each CREATE TABLE statement individually can create only one table. The syntax supported by MySQL does not allow multiple tables to be created simultaneously.
#bsdfish suggests using transactions, but DDL statements like CREATE TABLE cause implicit transaction commits. There's no way to execute multiple CREATE TABLE statements in a single transaction in MySQL.
I'm also curious why you would need to create two tables simultaneously. The only idea I could come up with is if the two tables have cyclical dependencies, i.e. they reference each other with foreign keys. The solution to that is to create the first table without that foreign key, then create the second table, then add the foreign key to the first table with ALTER TABLE ADD CONSTRAINT. Dropping either table requires a similar process in reverse.
Not with MS SQL Server. Not sure about mysql.
Can you give more info on why you'd want to do this? Perhaps there's an alternative approach.
I don't know, but I don't think you can do that. Why you want to do this?
Not in standard SQL using just the 'CREATE TABLE' statement. However, you can write multiple statements inside a CREATE SCHEMA statement, and some of those statements can be CREATE TABLE statements. Next question - does your DBMS support CREATE SCHEMA? And does it have any untoward side-effects?
Judging from the MySQL manual pages, it does support CREATE SCHEMA as a synonym for CREATE DATABASE. That would be an example of one of the 'untoward side-effects' I was referring to.
(Did you know that standard SQL does not provide a 'CREATE DATABASE' statement?)
I don't think it's possible to create more than one table with a 'CREATE TABLE' command. Everything really depends on what you want to do. If you want the creation to be atomic, transactions are probably the way to go. If you create all your tables inside a transaction, it will act as a single create statement from the perspective of anything going on outside the transaction.

How does a "Schema changed after the target table was created" error occur?

I hit this error while my web application was trying to execute a SELECT INTO on a MSSQL 2005 database. I really have two questions:
What does this error mean and how does this happen?
Is there a way to prevent these errors by coding in a different way?
Besides the obvious, that somebody changed the table while the code was executing, it could be a naming conflict with temp tables created in the SQL. It could be that there are two temp tables with different schemas, but they have the same name.
You can get this error if a database trigger(AFTER CREATE_TABLE) changes the table, when using SELECT INTO.
Also you can get this when you have the
SELECT * INTO #TABLE FROM TABLE
used within a stored procedure and it is run multiple times concurrently.
You have to specify dbo. as the schema for the first table.

View Temporary Table Created from Stored Procedure

I have a stored procedure in SQL 2005. The Stored Procedure is actually creating temporary tables in the beginning of SP and deleting it in the end. I am now debugging the SP in VS 2005. In between the SP i would want to know the contents into the temporary table. Can anybody help in in viewing the contents of the temporary table at run time.
Thanks
Vinod T
There are several kinds of temporary tables, I think you could use the table which is not dropped after SP used it. Just make sure you don't call the same SP twice or you'll get an error trying to create an existing table. Or just drop the temp table after you see it's content. So instead of using a table variable (#table) just use #table or ##table
From http://arplis.com/temporary-tables-in-microsoft-sql-server/:
Local Temporary Tables
Local temporary tables prefix with single number sign (#) as the first character of their names, like (#table_name).
Local temporary tables are visible only in the current session OR you can say that they are visible only to the current connection for the user.
They are deleted when the user disconnects from instances of Microsoft SQL Server.
Global temporary tables
Global temporary tables prefix with double number sign (##) as the first character of their names, like (##table_name).
Global temporary tables are visible to all sessions OR you can say that they are visible to any user after they are created.
They are deleted when all users referencing the table disconnect from Microsoft SQL Server.
Edit the stored procedure to temporarily select * from the temp tables (possibly into another table or file, or just to the output pane) as it runs..?
You can then change it back afterwards. If you can't mess with the original procedure, copy it and edit the copy.
I built a few stored procedures which allow you to query the content of a temp table created in another session.
See sp_select project on github.
The content of the table can be displayed by running exec sp_select 'tempdb..#temp' from no matter which session.
Bottom line: the default Visual Studio Microsoft debugger is not in the same session as the SQL code being executed and debugged.
So you can ONLY look at #temp tables by switching them to global ##temp tables or permanent tables or whatever technique you like best that works across sessions.
note: this is VERY different from normal language debuggers... and I suspect kept
that way by Microsoft on purpose... I've seen third party SQL debugger tools decades ago
that didn't have this problem.
There is no good technical reason why the debugger cannot be in the same session as your SQL code, thus allowing you to examine all produced contructs including #temp tables.
To expand on previous suggestions that you drop the data into a permanent table, you could try the following:
-- Get rid of the table if it already exists
if object_id('TempData') is not null
drop table TempData
select * into TempData from #TempTable
This helped me.
SELECT * FROM #Name
USE [TEMPDB]
GO
SELECT * FROM syscolumns
WHERE id = ( SELECT id FROM sysobjects WHERE [Name] LIKE '#Name%')
this gives the details of all the temp table