scrp.Options.ScriptForAlter -- I suppose it scripts an ALTER TABLE instead of a CREATE TABLE
scrp.Options.ScriptForCreateDrop -- I'd guess it scripts a DROP TABLE and only afterwards a CREATE TABLE ?
My DB is fairly large and I'm still using Management Studio for script generation, so I'd like to know if someone else already found out the meaning of those options.
Related
I am using SQL Server 2012. When I want to create a temporary table named #TBL1, or rerun my code, I get this error:
There is already an object named '#TBL1' in the database
So I added this code to my query:
IF OBJECT_ID('dbo.#TBL1', 'U') IS NOT NULL
DROP TABLE dbo.#TBL;
But it shows the same error message
Please give me a clue is to what is wrong
You need to make sure OBJECT_ID looks in the right place. Temporary tables live in tempdb:
IF OBJECT_ID('tempdb.dbo.#TBL1', 'U') IS NOT NULL
BEGIN
DROP TABLE dbo.#TBL;
END
Also seems there is a typo (#TBL1 vs. #TBL).
And while I am normally am a big fan of schema prefixes, for #temp tables it’s not necessary and actually hampers readability IMHO.
I am looking to set up a high availability architecture whereby two mirror databases exist (DB1 & DB2) that serve another database with views (DBV) on it. DB1 has the overnight ETL on it, whilst DBV looks at DB2 until the etl is complete on DB1, at which point its views switch to the underlying tables on DB1. Once the ETL is complete on DB1, DB2 is restored with DB1 data before the next day's ETL. The next day, DB1 and DB2 switch roles.
I am looking for a neater/more secure way of switching between the two views than running sp_executesql to run a dynamically built string. I will be looking to also do this on stored procedures from a staging database which need to have their scripts dynamically altered to use the correct database to run the ETL on. Essentially, I am looking to pass the USE statement dynamically and then execute the rest of the script outside of any dynamic statement.
I want to avoid sp_executesql for support reasons for other developers and also to get around any possible extensive concatenation of strings if the stored procedure/view gets particularly lengthy.
Any ideas / different approaches to high availability in this context would be welcome.
One option might be to create a copy of each view in DBV for both target databases - i.e.
some_schema.DB1_myview
some_schema.DB2_myview
and then use a synonym to expose the views under their final names.
CREATE SYNONYM some_schema.myview ON some_schema.DB1_myview
Your switch process would then need only to drop and recreate the synonyms, rather than the views themselves. This would still need to be done with a dynamic SQL statement, but the complexity would be much lower.
A downside would be that there would be a risk of the definitions of the underlying views getting out of sync.
Edit
At the cost of more risk of getting out of sync, it would be possible to avoid dynamic SQL altogether by creating (for instance) a pair of stored procedures each of which generated the synonyms for one database or the other. Your switch code would then only need to work out which procedure to call.
Have you considered renaming the databases as you switch things around? I.e. the following prints 1 followed by 2, nothing in DBV had to be modified:
create database DB1
go
use DB1
go
create table T (ID int not null);
insert into T(ID) values (1);
go
create database DB2
go
use DB2
go
create table T (ID int not null);
insert into T(ID) values (2);
go
create database DBV
go
use DBV
go
create view V
as
select ID
from DB1..T
go
select * from V
go
alter database DB1 modify name = DBt
go
alter database DB2 modify name = DB1
go
alter database DBt modify name = DB2
go
select * from V
Obviously better names than 1 and 2 may be used. This way, DB1 is always the one used for live and DB2 is used for any staging work.
I'm trying to create and execute a procedure that creates some tables. It won't recognize my database.
USE [db1]
go
create procedure version_1 as
update db1
set ver=1
where ver=0;
create table Staff_Titles(
title nvarchar(100) not null,
title_description nvarchar(200) null,
[..]
go
It compiles even though the db1 from update db1 is underlined. So is ver=1 and ver=0. After I try to execute it, it says
invalid object name
at USE [DB1] again even though, it's inside the stored procedures...
I tried refreshing the database, I tried looking for Edit -> IntelliSense but I can't find it, I tried Ctrl + shift + R, nothing worked.
The IntelliSense is telling you that it can't find a table called db1 in the db1 database. Make sure the table exists or if it's in a different schema, make sure to include the schema, like this:
update db1.schmaname.db1
set ver=1
where ver=0;
If you are trying to store version data, you have to add a table and a field to store this information. You can not update fields on a database, as there are no fields directly at the database level. You can create a table called "Versions" with a field called "ver".
CREATE TABLE Versions
(
[Ver] [int] NOT NULL,
CONSTRAINT [PK_Versions] PRIMARY KEY CLUSTERED (Ver ASC)
)
Then when you run the procedure it could insert a record to indicate that the tables have been updated with that version. Something like this:
insert into Versions
values (1)
Then if you ever need to query for the latest version you could use:
select max(Ver) Ver from Versions
You might want to try and clear the intellisense cache if you "just" created that Database. Use the keystroke Ctrl-Shift-R or Ctrl-R.
I have an application that uses a SQL Server database with several instances of the database...test, prod, etc... I am making some application changes and one of the changes involves changing a column from a nvarchar(max) to a nvarchar(200) so that I can add a unique constraint on it. SQL Server tells me that this requires dropping the table and recreating it.
I want to put together a script that will do the table drop, recreate it with the new schema, and then reinsert the data that was there previously all in one go, if possible, just to keep things simple for use when I migrate this change to production.
There is probably a good SQL Server way to do this but I'm just not aware of it. If I was using Mysql I would mysqldump the table and its contents, and use that as my script for applying that change to production. I can't find any export functionality in SQL server that will give me a text file consisting of inserts for all data in a table.
Use SQL Server's Generate Scripts command
right click on the database; Tasks -> Generate Scripts
select your tables, click Next
click the Advanced button
find Types of data to script - choose Schema and Data.
you can then choose to save to file, or put in new query window.
results in INSERT statements for all table data selected in bullet 2.
No need to script
here are two ways
1 use alter table ....alter column.....
example..you have to do 1 column at a time
create table Test(SomeColumn nvarchar(max))
go
alter table Test alter column SomeColumn nvarchar(200)
go
2 dump into a new table while converting the column
select <columns except for the columns you want to change>,
convert(nvarchar(200),YourColumn) as YourColumn
into SomeNewTable
from OldTable
drop old table
rename this table to the same table as the old table
EXEC sp_rename 'SomeNewTable', 'OldTable';
Now add your index
I have following script.
I don't know how to create new database in sql server 2005.
I run following script, and it create tables under model instead of seperate database. it look massy.
how can I create separate database.
I am copy some script here for your adive and course of action.
-----------------------------------------------------------
-- SQL Server 2000 Bible
-- Hungry Minds
-- Paul Nielsen
-- OBX Kites sample database - CREATE Database, Tables, and Procs
-- this script will drop an existing OBXKites database
-- and create a fresh new installation
-- related scripts:
-- OBXKites_Populate
-- T-SQL KEYWORDS go
-- DatabaseNames
-----------------------------------------------------------
-----------------------------------------------------------
-- Drop and Create Database
USE master
GO
IF EXISTS (SELECT * FROM SysDatabases WHERE NAME='OBXKites')
DROP DATABASE OBXKites
go
-- This creates 1 database that uses 2 filegroups
CREATE DATABASE OBXKites
ON PRIMARY
(NAME = 'OBXKites', FILENAME = 'D:\SQLData\OBXKites.mdf'),
FILEGROUP Static
(NAME = 'OBXKitesStatic', FILENAME = 'c:\SQLData\OBXKitesStatic.ndf')
LOG ON (NAME = 'OBXKitesLog', FILENAME = 'c:\SQLData\OBXKites.ldf')
go
-- set to Full Log
go
SET QUOTED_IDENTIFIER ON
go
USE OBXKites
go
-----------------------------------------------------------
-----------------------------------------------------------
-- Create Tables, in order from primary to secondary
CREATE TABLE dbo.OrderPriority (
OrderPriorityID UNIQUEIDENTIFIER NOT NULL ROWGUIDCOL DEFAULT (NEWID()) PRIMARY KEY NONCLUSTERED,
OrderPriorityName NVARCHAR (15) NOT NULL,
OrderPriorityCode NVARCHAR (15) NOT NULL,
Priority INT NOT NULL
)
ON [Static]
go
CREATE DATABASE OBXKites
ON PRIMARY
(NAME = 'OBXKites', FILENAME = 'D:\SQLData\OBXKites.mdf'),
FILEGROUP Static
(NAME = 'OBXKitesStatic', FILENAME = 'c:\SQLData\OBXKitesStatic.ndf')
LOG ON
(NAME = 'OBXKitesLog', FILENAME = 'c:\SQLData\OBXKites.ldf')
go
This code in your script should create a new database. If no error occurrs in the process.
Can you simplify it down? or do you have to do all of that checking?
If it can be simplified I beileve some code such as:
CREATE DATABASE OBXKites
USE OBXKites
CREATE TABLE OrderPriority(syntax)
If simple code like this doesn't work, you may have deeper issues with rights or files or something as suggested by queen3 just before me.
Afterthought: At my school we were having issues like this as well I believe... after a few classes we finally arived at the conclusion that we didn't have rights to add files to the program files directory on the lab computers and SQL wasn't reporting the error to us.
Are there any errors in output? The script itself does already do what you requested.
I'd suspect that you incorrectly specified filenames - some of them are on drive C:, and some on drive D:.
Your script in question will create the tables in the OBXKites database (see the USE OBXKites statement in your script)
Does the OBXKites database already exist in your server instance? If so, that's probably why it appears that it is creating the tables in the current database, since the script is effectively removing and recreating the OBXKites database. If you need a different name for the database, find all instances of "OBXKites" in your script above after the line that reads "This creates 1 database that uses 2 filegroups" and rename it to the new database name you desire.
The only other option could be that the script has execution errors creating the database, if your user account lacks the proper permissions to do so. However, the script continues to execute, creating the tables in the current database you are logged in to, which is why you are seeing the tables there.
Create DataBase In Ubuntu Terminal
my database name is database_name
you can use anything
create database database_name;
How to select this database to create a table inside it.
use database_name;