Saturday, November 4, 2017

Creating a SQL server Login in SSMS

Through SSMS object explorer: Expand security node-> Right click->New Login. Type user name in the Login name-> Click OK.
Through powershell: SQLCMD -S Computername
Through Query for windows authentication
USE DATABASE;
GO
CREATE LOGIN
[DOMAINNAME\USERNAME]
FROM WINDOWS;
GO
Through Query for sql server authentication
USE DATABASE;
GO
CREATE LOGIN
[DOMAINNAME\USERNAME]
WITH PASSWORD= N'PASSWORD';
GO
Through Query for sql server authentication and user changing password on next login
USE DATABASE;
GO
CREATE LOGIN
[DOMAINNAME\USERNAME]
WITH PASSWORD= N'PASSWORD'
MUST_CHANGE,
CHECK POLICY=ON,
CHECK EXPIRATION=ON;
GO

Difference between Varchar2, Char, NVarchar2 and Nchar Datatypes

Varchar2 - Stores variable length character up to a maximum of 4000 characters. variable length character data is character data in which values in different rows can have a different number of characters.
Eg: firstname VARCHAR2(30)
Char - stores fixed-length character data up to a maximum of 2000 characters. Fixed-length character data is character data in which the data values for different rows all have the same number f characters.
Eg: class CHAR(2)
NVarchar2 and Nchar - Use if input data in character set is data other than standard English. (Address 256 character limitation of ASCII coding)

Friday, November 3, 2017

Creating a user in SSMS

Example 1

CREATE DATABASE SAMPLE;
CREATE LOGIN GUEST
WITH PASSWORD= '123#$@AeioU';
USE SAMPLE;
GO
CREATE USER Angela FOR LOGIN GUEST;
GO

Example 2

CREATE DATABASE SAMPLE;
CREATE LOGIN GUEST
WITH PASSWORD= '123#$@AeioU';
USE SAMPLE;
GO
CREATE USER Ammu FOR LOGIN GUEST WITH DEFAULT_SCHEMA=Student;
GO



Database Trigger

A trigger is a special kind of stored procedure that executes when an INSERT, UPDATE, or DELETE statement modifies the data in a specified table or when a DDL (CREATE, ALTER, or DROP) occurs or when a database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN) occurs. In simple terms, a trigger is an action that is performed behind-the scenes when an event occurs on a table, view, schema or a database .
Creating a Trigger
Creates a DML, DDL, or logon trigger.
DML triggers execute when a user tries to modify data through a data manipulation language (DML) event. DML events are INSERT, UPDATE, or DELETE statements on a table or view.

DDL triggers execute in response to a variety of data definition language (DDL) events. These events primarily correspond to Transact-SQL CREATE, ALTER, and DROP statements, and certain system stored procedures that perform DDL-like operations.  A DDL trigger gives you the opportunity to do some administrative work in response to the event. For example, you will get a notification, or notify someone else using an automatically generated email, that an object (and what object) has been created, or you can use a DDL trigger to discard the operation.

CREATE TRIGGER safety
ON DATABASE
FOR DROP_TABLE, ALTER_TABLE
AS
   PRINT 'You must disable Trigger "safety" to drop or alter tables!'
   ROLLBACK ;
Logon triggers fire in response to the LOGON event that is raised when a user sessions is being established. All messages originating inside the trigger that would typically reach the user, such as error messages and messages from the PRINT statement, are diverted to the SQL Server error log.  Logon triggers do not fire if authentication fails. To audit and control server sessions. Logon triggers are basically used for restricting logins to Sql Server, restricting the number of sessions for a specific login, restricting user from logging-in outside permitted hours.
Example

Create a login guest by executing the following script:


-- Create a login
CREATE LOGIN guest WITH PASSWORD = 'GuestPass1'

--Create Trigger

CREATE TRIGGER connection_limit_trigger
ON ALL SERVER FOR LOGON
AS
BEGIN
 IF ORIGINAL_LOGIN() = 'guest' AND
  (Select count(*) from sys.dm_exec_sessions
      WHERE is_user_process=1 and orginal_login_name = 'guest') > 3
 BEGIN
  PRINT 'You are not authorized to login'
  ROLLBACK
 END
END

DML Trigger

AFTER/FOR INSERT Triggers
An insert trigger is a DML trigger that acts when a new record is added to its intended table. such trigger uses INSERT keyword.

-- SQL Server Syntax 
-- Trigger on an INSERT, UPDATE, or DELETE statement to a table or view (DML Trigger

CREATE [ OR ALTER ] TRIGGER [ schema_name . ]trigger_name  
ON { table | view }  
[ WITH [ ,...n ] ] 
{ FOR | AFTER | INSTEAD OF }  
{ [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] }  
[ WITH APPEND ] 
[ NOT FOR REPLICATION ]  
AS { sql_statement  [ ; ] [ ,...n ] | EXTERNAL NAME }


Eg:

CREATE TRIGGER Sales.ForEmployees

ON Sales.Employees

AFTER INSERT

AS

BEGIN

INSERT INTO Sales.DatabaseOperations

VALUES(default,N'Customers', SUSER_SNAME(),N'Processed salary', GETDATE())

END

GO
Trigger name: Sales.ForEmployees
Table which trigger is created: Sales.Employees

If some value gets inserted into Sales.Employees table, trigger will occur and insert all the details( name of table, who performed, what action, time the action is performed) about insertion in another table called Sales.DatabaseOperations.

AFTER/FOR UPDATE Triggers
whenever a record has been updated on a table, DML trigger will be evoked.
CREATE TRIGGER Sales.Update
ON Sales.Employee
AFTER UPDATE
AS
BEGIN
    INSERT INTO Sales.DatabaseOperations
    VALUES(default, N'Employees', SUSER_SNAME(),
    N'updated employee record.',GETDATE());

END
GO

AFTER/FOR DELETE Triggers
whenever a record has been deleted from a table, DML trigger will be evoked.
CREATE TRIGGER Sales.Delete
ON Sales.Employee
AFTER DELETE
AS
BEGIN
    INSERT INTO Sales.DatabaseOperations
    VALUES(default, N'Employees', SUSER_SNAME(),
    N'deleted employee record.',GETDATE());

END
GO
INSTEAD OF DML Triggers
Trigger will get evoked before the action takes place. basically INSTEAD OF trigger prevent a user from adding, modifying or deleting a record. 

Example:

CREATE TRIGGER Sales.Event
ON Sales.Employee
INSTEAD OF INSERT
AS
BEGIN
    INSERT INTO Sales.DatabaseOperations
    VALUES(default, N'Employees', SUSER_SNAME(),
    N'User tried to insert employee record.',GETDATE());

END
GO

There are INSTEAD OF INSERT, INSTEAD OF UPDATE and INSTEAD OF DELETE Triggers.

Using 'With Execute As' in a trigger: - Allows an user to execute a trigger on behalf of someone
Example:
CREATE TRIGGER Sales.WithEmployee
ON Sales.Employee
WITH EXECUTE AS N'JIS'
AFTER INSERT
AS
BEGIN
INSERT INTO Sales.DatabaseOperations
VALUES(default, N'Employees', SUSER_NAME(), N'inserts an employee record', GETDATE());
END
GO
***** An AFTER trigger can be applied to a table only.  An INSTEAD OF trigger can be associated with either a table or a view. A table cannot have more than one INSTEAD OF INSERT trigger,
DDL Trigger
Trigger that acts when a certain type of DDL event fires. (creation, modification and removal of an object, not its records)

Example:
CREATE TRIGGER Logcreationoftable
ON DATABASE
FOR CREATE_TABLE
AS
BEGIN
INSERT INTO Sales.DatabaseOperations
VALUES(SUSER_NAME(), N'inserts an employee record', GETDATE());
END
GO

when new table is created, trigger runs, updates the name of user who created the table, date and time of table creation and message.

WITH EXECUTE AS

The user or login account is impersonated for the duration of the session or module execution, or the context switch is explicitly reverted.

CREATE PROCEDURE AccessMyTable
WITH EXECUTE AS 'Mary'
AS SELECT * FROM dbo.MyTable;

Wednesday, November 1, 2017

Database.Schema.Table

Most of the database beginners used to get confused with database, schema and table.

Database:  

A database maintains information about various types of objects (inventory), events (transactions), people (employees), and places (warehouses).  It is an integrated collection of logically related
data elements. Rows are also called records and columns are also called fields. 
Primary Keys are a column that identifies a unique row in a table. In the table DimCustomer given below, CustomerKey is Primary Key. It can act as a foreign key in different table. CustomerKey acts as a foreign key in FactInternetSales table.  A relational database carries data in the form of tables and uses foreign keys to represent relationships

Eg:

Create Database

Method 1
  • Open Microsoft SQL Management Studio.
  • Expand the Microsoft SQL Server node where you want to create the database.
  • Right click the Databases node and then click New Database.
  • Type the database name in the dialog box, for example, ADMINISTRATION, and then click OK
Method 2

Write query

CREATE DATABASE databasename;
Tip: Make sure you have admin privilege before creating any database. Once a database is created, you can check it in the list of databases with the following SQL command: SHOW DATABASES;

Schema

A schema is a distinct namespace to facilitate the separation, management, and ownership of database objects. It is a separate entity within the database. It removed the tight coupling of database objects and owners to improve the security administration of database objects. They logically group tables, procedures, views together. For Example, all customer-related objects can be included in the customer schema, all registration related information of students can be included in Registration schema etc. Also, permissions can be provided to just one schema, so that users can only see the schema they have access to and nothing else.
Create a schema
Method 1
  1. In Object Explorer, expand the Databases folder.
  2. Expand the database in which to create the new database schema.
  3. Right-click the Security folder, point to New, and select Schema.
  4. In the Schema - New dialog box, on the General page, enter a name for the new schema in the Schema name box.
Method 2

Write query inside database

CREATE SCHEMA schemaname AUTHORIZATION username

Eg 1: create a schema called STUDENT with the user STUDENT as the owner.
CREATE SCHEMA STUDENT AUTHORIZATION STUDENT
Eg 2: Create a schema EMPLOYEE that has details of employee table. Give authority on the table to user JIS. (Ran query one by one. )

CREATE SCHEMA EMPLOYEE;

CREATE TABLE EMP (EMPNO  SMALLINT NOT NULL,
                        ENAME    VARCHAR(40),
                        EPHONE INTEGER);
 GRANT ALL ON EMP TO JIS;

Table

A relational database system contains one or more objects called tables. The data or information for the database are stored in these tables. Tables are uniquely identified by their names and are comprised of columns and rows. Columns contain the column name, data type, and any other attributes for the column.

CREATE TABLE table_name (
    column1 datatype,
    column2 datatype,
    column3 datatype,
   ....
);


ADMINISTRATION.EMPLOYEE.EMP => Database.Schema.Table

who is Database Owner?


     Whenever a new database is created, the server wants to keep track of who created that database. This is known as the database owner. By default, Microsoft SQL Server creates a special account named dbo(for database owner). When you create a database but do not specify the owner, this account is used. The dbo account is also given rights to all types of operations that can be performed on the database. When you install Microsoft SQL Server, it also installs 4 databases named master, model, msdb, and tempdb. You should avoid directly using them, unless you know exactly what you are doing.

GEN AI

  Stay Tuned....