How - create and use database directly after creation in SQL Server? - sql

I created a sql script to check if a database already exist, if it already exists it deletes and re-creates.
After I would like to connect it directly after its creation for creating tables ..
Here is my code but it does not work.
He announces an error message
Msg 911, Level 16, State 1, Line 10
Database 'Arms2' does not exist. Make sure that the name is entered correctly.
My script
IF EXISTS (select * from sys.databases where name = 'Arms2')
BEGIN
DROP DATABASE Arms2
PRINT 'DROP DATABASE Arms2'
END
CREATE DATABASE Arms2;
PRINT 'CREATE DATABASE Arms2'
USE Arms2
CREATE TABLE .....

Put a GO statement after the CREATE...
...
CREATE DATABASE Arms2;
PRINT 'CREATE DATABASE Arms2'
GO
USE Arms2

Related

Get list of SQL server databases which files have been deleted

My goal is getting list of SQL server databases which files have been deleted.
In other words. I attach a db from mount, then close the mount so actually I have the attached db without files.
At first it seemed to be easy. Just pretty easy select:
SELECT
'DB_NAME' = db.name,
'FILE_NAME' = mf.name,
'FILE_TYPE' = mf.type_desc,
'FILE_PATH' = mf.physical_name
FROM
sys.databases db
INNER JOIN sys.master_files mf
ON db.database_id = mf.database_id
WHERE
--and specific condition here
But it turned out differently. Sql server has almost the same information about a regular database and a database which doesn't have files. So I had to try something else.
Further I tried to use state of database. And it was quite strange.
Unfortunately the following query gives me wrong(or not actual information):
SELECT state
FROM sys.databases
WHERE name = N'TestDB'
state
-----
0
And 0 means ONLINE according to this link
But actually the database has RECOVERY_PENDING state. It looks like that sql server information about my TestDB us out of date and should be refreshed. But I have no idea how to achieve this. But after executing any of following query this info(db state) is being refreshed:
EXEC sp_helpdb N'TestDB'
ALTER DATABASE N'TestDB' SET SINGLE_USER WITH ROLLBACK IMMEDIATE
USE N'TestDB'
--etc
--all requests are terminated with the same error
Msg 5120, Level 16, State 101, Line 10
Unable to open the physical file "C:\MOUNT\b4c059e8-3ba6-425f-9a2a-f1713e7719ca\TestDB.mdf". Operating system error 3: "3(The system cannot find the path specified.)".
File activation failure. The physical file name "C:\MOUNT\b4c059e8-3ba6-425f-9a2a-f1713e7719ca\TestDB_log.ldf" may be incorrect.
File activation failure. The physical file name "C:\MOUNT\b4c059e8-3ba6-425f-9a2a-f1713e7719ca\TestDB_log-2.ldf" may be incorrect.
Msg 5181, Level 16, State 5, Line 10
Could not restart database "TestDB". Reverting to the previous status.
Msg 5069, Level 16, State 1, Line 10
ALTER DATABASE statement failed.
So do you have any idea ?
And also I've asked the question looks like this here differently.
Finally, I've found what i actually need.
I can chech whether the specific file exists or not by sql server:
CREATE FUNCTION dbo.fn_FileExists(#path varchar(512))
RETURNS BIT
AS
BEGIN
DECLARE #result INT
EXEC master.dbo.xp_fileexist #path, #result OUTPUT
RETURN cast(#result as bit)
END;
GO
So i just need to execute the function above for each file which i can get by executing for example following query:
SELECT
DISTINCT 'FILE_PATH' = physical_name
FROM sys.master_files

SQL SERVER: I would like to transfer my data to another column of the same table before droping the first one

I am having problems with some of my SQL scripts on SQL SERVER, indeed I am trying to transfer data from a column A to a column B of the same table and then drop the column B,
However my problem is that I have to check for the existence of A beforehand because the code is meant to be executed on a server where I don't have access (I work as a third party developper on a professionnal app)
Here is my code:
-- Export the data from the column name
-- Drop the column name
USE p_mynacellelocation_db_ChecklistWPF
GO
IF COL_LENGTH('model_trolley_part','name') IS NOT NULL
BEGIN
UPDATE model_trolley_part
SET name_en=[name];
ALTER TABLE model_trolley_part
DROP COLUMN [name];
END
In the case of the column name being non existent I would like not to do anything
However on execution of the code in a database where the column name is non existent SQL Server returns me:
Msg 207, Level 16, State 1, Line 12 Invalid column name 'name'.
Instead of jumping through all these hoops simply rename your original column.
https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-rename-transact-sql?view=sql-server-2017
exec sp_rename 'model_trolley_part.name', 'name_en', 'COLUMN'
You need to use dynamic SQL for this. The reason is that the parser will try to validate your code, even the code that won't be executed because its IF condition wouldn't be met.
The parser is smart enough to see there is no table named name, but it's not smart enough to realize that the code shouldn't get executed because of the IF, so it raises a parsing error.
Using dynamic SQL in the BEGIN..END block after the IF hides this from the parser so it will execute.
Try this:
IF EXISTS(SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'myTableName'
AND COLUMN_NAME = 'ColumnA')
BEGIN
// your update and drop code goes here
END
you might want to check your account privileges if you are modifying table structure etc..

SQL Server 2008: DROP PROCEDURE error

I try to execute this command:
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.njams_test_sql_2.[PROC_CHECK_TRACE_SETTINGS]') AND type in (N'P', N'PC'))
DROP PROCEDURE dbo.njams_test_sql_2.[PROC_CHECK_TRACE_SETTINGS]
GO
But I'm getting this error:
Msg 166, Level 15, State 1, Line 1
'DROP PROCEDURE' does not allow specifying the database name as a prefix to the object name
What I'm trying to do is to delete all objects in a database, so that the database is empty. I'm using Microsoft SQL Server 2014 Management Studio.
As the error clearly says - you cannot use the database name as a prefix in a DROP PROCEDURE.
You need to make sure you're connected to the correct database and then you need to execute
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.njams_test_sql_2.[PROC_CHECK_TRACE_SETTINGS]') AND type in (N'P', N'PC'))
DROP PROCEDURE [PROC_CHECK_TRACE_SETTINGS]
GO
You need to change the order of database name and schema.
This is wrong:
DROP PROCEDURE dbo.njams_test_sql_2.[PROC_CHECK_TRACE_SETTINGS]
This is correct:
DROP PROCEDURE njams_test_sql_2.dbo.[PROC_CHECK_TRACE_SETTINGS]
Or, you can just leave them away. Then the current database and the default schema (most likely dbo) are used:
DROP PROCEDURE [PROC_CHECK_TRACE_SETTINGS]

TABLE DROP statement

I am trying to drop a table that I created in SQL Server. I typed the command as follows:
DROP TABLE [Exercise2].
I received the following error message:
Msg 3701, Level 11, State 5, Line 1
Cannot drop the table 'Exercise2', because it does not exist or you do not have permission.
I have dropped multiple tables trying to clean out my database, but this one will not drop and I'm not sure why.

Create Database and Table Conditionally

I'm trying to write a small script to create a database if it doesn't exist, and create a table for that database if the table doesn't exist. What I have is this:
IF (db_id('db') is null) BEGIN
print 'Must create the database!';
CREATE DATABASE db;
END
USE db;
IF (object_id('test_table', 'U') is null) BEGIN
print 'Must create the table!';
CREATE TABLE test_table (
id int
);
END
I'm getting a strange error with this:
Database 'db' does not exist. Make sure that the name is entered correctly.
I'm guessing that it's parsing the script before running it and finding that 'db' doesn't exist, so it can't use it.
There must be a solution to this. Any help is appreciated.
SOLVED!
I realised 5 minutes after posting that the GO keyword solves the problem. Here is the fixed code:
IF (db_id('db') is null) BEGIN
print 'Must create the database!'
CREATE DATABASE db;
END
GO
USE db
IF (object_id('test_table', 'U') is null) BEGIN
print 'Must create the table!';
CREATE TABLE test_table (
id int
);
END
Sorry for wasting everyone's time.
SQL statements are parsed as one batch unless you break them apart. In SQL Server, you can use GO to do this. In both MySQL and SQL Server, you can use BEGIN and END.
If you want to commit the separate blocks to the database in different instances you can use BEGIN TRANS / COMMIT TRANS and START TRANSACTION / COMMIT for SQL Server and MySQL, respectively.
Something along the lines of Check if table exists in SQL Server would probably work (With a slight change)
IF (NOT EXISTS (SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'TheSchema'
AND TABLE_NAME = 'TheTable'))
BEGIN
--Do Stuff
END
I might suggest using the built-in SQL syntax -
CREATE DATABASE name IF NOT EXISTS;
And subsequently
CREATE TABLE name(definition) IF NOT EXISTS;