How to add a new schema to sql server 2008? - sql-server

How do you add a new schema to a database? I am creating a new table and would like to select my own schema from the properties list, but I don't know how to create it. I am using SQL Server Management 2008.

Use the CREATE SCHEMA syntax or, in SSMS, drill down through Databases -> YourDatabaseName -> Security -> Schemas. Right-click on the Schemas folder and select "New Schema..."

Here's a trick to easily check if the schema already exists, and then create it, in it's own batch, to avoid the error message of trying to create a schema when it's not the only command in a batch.
IF NOT EXISTS (SELECT schema_name
FROM information_schema.schemata
WHERE schema_name = 'newSchemaName' )
BEGIN
EXEC sp_executesql N'CREATE SCHEMA NewSchemaName;';
END

I use something like this:
if schema_id('newSchema') is null
exec('create schema newSchema');
The advantage is if you have this code in a long sql-script you can always execute it with the other code, and its short.

Best way to add schema to your existing table: Right click on the specific table-->Design -->
Under the management studio Right sight see the Properties window and select the schema and click it, see the drop down list and select your schema. After the change the schema save it. Then will see it will chage your schema.

You can try this:
use database
go
declare #temp as int
select #temp = count(1) from sys.schemas where name = 'newSchema'
if #temp = 0
begin
exec ('create SCHEMA temporal')
print 'The schema newSchema was created in database'
end
else
print 'The schema newSchema already exists in database'
go

In SQL Server 2016 SSMS expand 'DATABASNAME' > expand 'SECURITY' > expand 'SCHEMA' ; right click 'SCHEMAS' from the popup left click 'NEW SCHEMAS...' add the name on the window that opens and add an owner i.e dbo click 'OK' button

Related

SQL Server 2008 R2: 'CREATE/ALTER VIEW' does not allow specifying the database name as a prefix to the object name

I have to 2 databases DB1 and DB2.
I have a view called View1 which is stored in the database DB2. Now I want to ALTER VIEW from DB1 database.
My attempt:
ALTER VIEW DB2..View1
AS
SELECT * FROM DB2..Test;
But I'm getting an error:
'CREATE/ALTER VIEW' does not allow specifying the database name as a prefix to the object name
It is really simple: you need to change the database
USE DB2
GO
ALTER VIEW View1
...
In my case I'm trying to run a script to create/alter a view in different database, so I'm using EXEC (...) to create my views.. But I hit a bit of a paradox:
EXEC ('CREATE VIEW...') will not let you specify the database. You have to switch to that database to create the view.
But you can't do EXEC ('USE [db]; CREATE VIEW...') as CREATE VIEW will demand it be the first command.
I got around this problem feeling like I went Inception:
        EXEC('USE [db]; EXEC('CREATE VIEW'))
Comments are self explanatory. You need to be working in the DataBase your view is for/from. Switch your connection to DB2 and you should be able to CREATE and ALTER a/your view. From MSDN
I was connected to the same database server:DB1 in Azure Data Studio where I wanted the view, and getting the error from this:
CREATE OR ALTER VIEW DB1.dbo.my_View AS
SELECT ...
I removed the prefix and this worked:
CREATE OR ALTER VIEW my_View AS
SELECT ...

Create User from a different DB in SQL Server

Is there any way I can create a user on a database from the master DB(or any other DB)
IF EXISTS (SELECT 1 FROM j_test.sys.database_principals WHERE name = N'test_user')
DROP USER j_test.[test_user]; --doesnt't work.
You either need to change the context to that database or dynamically go there:
EXEC j_test..sp_executesql N'DROP USER test_user;';
Logins are done at the server level, I usually create them from the [master] database. Just my convention.
Users are done at the database level. You need to have your context set to that database. The USE command allows you to switch between databases.
This snippet is from my blog that shows a hypothetical database [BSA] with a schema named [STAGE].
-- Which database to use.
USE [master]
GO
-- Delete existing login.
IF EXISTS (SELECT * FROM sys.server_principals WHERE name = N'BSA_ADMIN')
DROP LOGIN [BSA_ADMIN]
GO
-- Add new login.
CREATE LOGIN [BSA_ADMIN] WITH PASSWORD=N'M0a2r0c9h11$', DEFAULT_DATABASE=[BSA]
GO
-- Which database to use.
USE [BSA]
GO
-- Delete existing user.
IF EXISTS (SELECT * FROM sys.database_principals WHERE name = N'BSA_ADMIN')
DROP USER [BSA_ADMIN]
GO
-- Add new user.
CREATE USER [BSA_ADMIN] FOR LOGIN [BSA_ADMIN] WITH DEFAULT_SCHEMA=[STAGE]
GO

replace table by other table

We have this current database which we need to replace some tables by anther tables from backup database. we are using sql server 2008 r2 and I want to know how to do overwrite or replace current tables by new table having same structures. thanks in advance.
step1:
Restore the backup to the same server with a different name.
Say if your actual database is "MYDB", you can restore the backup and name "MYBD_BKUP" something like that.
You can restore database using SQL server management studio
Right click on Databases>Restore Database
Step2: Once restore is success full, you can delete all the tables (to be deleted) from MYDB
Step3:
transfer table from MYDB_BKUP
USE MYDB
select * into <table1> from MYDB_BKUP.dbo.<table1>
etc.. for each table
IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE
TABLE_SCHEMA = 'MySchema' AND TABLE_NAME = 'MyTable'))
BEGIN
DROP TABLE MyTable;
END
put this query in your backup database script, for each table you want to replace. like..
IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE
TABLE_SCHEMA = 'YourSchemaName' AND TABLE_NAME = 'table_staff'))
BEGIN
DROP TABLE table_staff;
END
If u want to replace the whole database with backup database then...
Right Click on Database to which u want to replace
Go to Task
Go to Restore...
check from file radio button
Select backup file
Now your .bak file will show in lower area and check this file by clicking on checkbox
Select options of left side in popup
check checkbox.. override existing
click ok
This will replace your current database with backup database

Where does a Server trigger save in SQL Server?

A couple of days ago , I was practicing and I wrote some triggers like these :
create trigger trg_preventionDrop
on all server
for drop_database
as
print 'Can not Drop Database'
rollback tran
go
create trigger trg_preventDeleteTable
on database
for drop_table
as
print 'you can not delete any table'
rollback tran
But the problem is I don't know where it has saved and How can I delete or edit those.
Thank you
Server Trigger
You can see them here
select * from sys.server_triggers
To drop use this syntax
drop trigger trg_preventionDrop on all server
In Management Studio they are under the "Server Objects" -> "Triggers" node
Database Trigger
You can see them here
select * from yourdb.sys.triggers
To drop use this syntax
drop trigger trg_preventDeleteTable on database
In Management Studio they are under the "Databases" -> "yourdb" -> "Programmability" -> "Database Triggers" node
trigger on a particular table resides in "DataBase" -> "YourDb" -> "YourTable" -> "Trigger" folder in Management Studio
also one can find the trigger on a particular table by execution the following sql:
EXEC sp_helptrigger yourtablename

How do i recreate a trigger in SQL Server?

i use the statement drop trigger if exist TRIGGER in sqlite but sql server doesnt like the if statement. (i guess exist is the offending word). I do this right next to my create trigger statement because i want to drop older triggers with the same name so i can replace it with this new one.
How do i do this in SQL server?
in SQL Server Management Studio (and, I think in Query Analyzer) right-click the trigger in the explorer, and choose the Script-as option, choose 'Drop Trigger' in clipboard, and SSMS will create the T-SQL syntax for you to drop that trigger.
Sorry I haven't given you T-SQL you can copy and paste, but this way you'll know how to do it for next time.
You can check for the existence of a specific Trigger like so.
IF EXISTS
(
select name
from sys.objects
where type='TR' and name ='Trigger Name'
)
BEGIN
--Add your Trigger create code here
END
I find this to be a more compact SQL Server equivalent to MySQL's DROP TRIGGER IF EXISTS syntax:
IF OBJECT_ID('XXXX', 'TR') IS NOT NULL
DROP TRIGGER XXXX
I'd use something like:
IF objectproperty(object_id('dbo.xxx'), 'isTrigger') = 1
DROP PROCEDURE dbo.xxx
GO
CREATE TRIGGER dbo.xxx [etc]
replacing xxx with your trigger name (and dbo with the relevant schema, if necessary).
Alternatively, you could just use
ALTER TRIGGER dbo.xxx [etc]
Since version 2016 this syntax is also supported by Microsoft SQL Server:
DROP TRIGGER IF EXISTS trigger_name

Resources