MS SQL SERVER 2008 – New Features | GROUPING SETS, ROLLUP, CUBE, Row Constructors, etc
Compatibility Level:
ALTER DATABASE SET COMPATIBILITY_LEVEL replaces sp_dbcmptlevel for setting the database compatibility level.
ALTER DATABASE database_name
SET COMPATIBILITY_LEVEL = { 80 90 100 }
COMPATIBILITY_LEVEL Is the version of SQL Server with which the database is to be made compatible. The value must be one of the following:
80 = SQL Server 2000
90 = SQL Server 2005
100 = SQL Server 2008
Compound Operators:
Operators that perform an operation and set a variable to the result, for example SET @x += 2, are available.
DECLARE @x1 int = 27; SET @x1 += 2; SELECT @x1 AS Added_2;
CONVERT Function:
The CONVERT function is enhanced to allow conversions between binary and character hexadecimal values.
CAST ( expression AS data_type [ (length ) ])
CONVERT ( data_type [ ( length ) ] , expression [ , style ] )
Date and Time Functionality:
SQL Server 2008 introduces four new date and time data types:
1. DATE
2. TIME
3. DATETIME2
4. DATETIMEOFFSET
It also includes support for the ISO week-date system.
DATEPART ( datepart , date )
SELECT DATEPART (TZoffset, 2007-05-10 00:00:01.1234567 +05:10); SELECT DATEPART(millisecond, '00:00:01.1234567'); -- Returns 123 SELECT DATEPART(microsecond, '00:00:01.1234567'); -- Returns 123456 SELECT DATEPART(nanosecond, '00:00:01.1234567'); -- Returns 123456700
GROUPING SETS:
The GROUPING SETS, ROLLUP, and CUBE operators are added to the GROUP BY clause. There is a new function, GROUPING_ID(), that returns more grouping-level information than the existing GROUPING() function. The non-ISO compliant WITH ROLLUP, WITH CUBE, and ALL syntax is deprecated.
For more info: http://msdn.microsoft.com/en-us/library/bb522495.aspx
MERGE Statement:
This new Transact-SQL statement performs INSERT, UPDATE, or DELETE operations on a target table based on the results of a join with a source table. The syntax allows you to join a data source with a target table or view, and then perform multiple actions based on the results of that join.
For moe info: http://msdn.microsoft.com/en-us/library/bb510625.aspx
SQL Dependency Reporting:
SQL Server 2008 introduces a new catalog view and system functions to provide consistent and reliable SQL dependency reporting. You can use sys.sql_expression_dependencies, sys.dm_sql_referencing_entities, and sys.dm_sql_referenced_entities to report on cross-server, cross-database, and database SQL dependencies for both schema-bound and non-schema-bound objects.
Table-Valued Parameters:
The Database Engine introduces a new parameter type that can reference user-defined table types. Table-valued parameters can send multiple rows of data to a SQL Server statement or routine (such as a stored procedure or function) without creating a temporary table.
For more info: http://msdn.microsoft.com/en-us/library/bb510489.aspx
Transact-SQL Row Constructors:
Transact-SQL is enhanced to allow multiple value inserts within a single INSERT statement.
INSERT INTO dbo.Customers(custid, companyname, phone, address) VALUES (1, 'cust 1', '(111) 111-1111', 'address 1'), (2, 'cust 2', '(222) 222-2222', 'address 2'), (3, 'cust 3', '(333) 333-3333', 'address 3'), (4, 'cust 4', '(444) 444-4444', 'address 4'), (5, 'cust 5', '(555) 555-5555', 'address 5'); --- AND --- SELECT * FROM (VALUES (1, 'cust 1', '(111) 111-1111', 'address 1'), (2, 'cust 2', '(222) 222-2222', 'address 2'), (3, 'cust 3', '(333) 333-3333', 'address 3'), (4, 'cust 4', '(444) 444-4444', 'address 4'), (5, 'cust 5', '(555) 555-5555', 'address 5')) AS C(custid, companyname, phone, address);
Source: MSDN
SQL Basics – Rename or Change DataType of a Column in SQL Server
In my [previous post] we saw how to create a new Database and a new Table. We also saw how to [ADD/DROP] columns in a table.
Today we will see how to Rename a Column and Change its datatype.
–> To Rename an existing column in a table you can use the system Stored Procedure sp_rename, and the syntax is:
EXECUTE sp_rename 'schema.Table.ColumnName', 'NewColumnName', 'COLUMN'
–> And to change column datatype use simple ALTER TABLE statement, like:
ALTER TABLE table_name
ALTER COLUMN ColumnName new_Datatype
Check video on how to Rename and Change column datatype in a Table:
–> SQL Script used in the above demo:
USE [Demo] GO -- Create a sample table: CREATE TABLE [dbo].[Employee]( [EmployeeID] int NOT NULL, [EmployeeName] nvarchar(100) NOT NULL, [Gender] nchar(1) NULL, [DOB] datetime NULL, [DOJ] datetime NULL, [DeptID] int NULL ) INSERT INTO [dbo].[Employee] VALUES (1, 'MANOJ PANDEY', 'M', '1990-01-01', '2010-01-01', 101) INSERT INTO [dbo].[Employee] VALUES (2, 'JHON K', 'M', NULL, '2010-01-01', NULL) INSERT INTO [dbo].[Employee] ([EmployeeID], [EmployeeName]) VALUES (3, 'Brock H') GO SELECT * FROM [dbo].[Employee] GO -- Rename a column: EXECUTE sp_rename N'dbo.Employee.MgrID', N'ManagerID', 'COLUMN' GO -- Change datatype of column: ALTER TABLE [dbo].[Employee] ALTER column ManagerID BIGINT GO
SQL Basics – ADD or DROP (remove) Columns in a Table in SQL Server
In my [previous post] we saw how to create a new Database and a new Table.
Today we will see how to ADD a new column to a table and DROP an existing column from a table.
To ADD or DROP columns you have to use the ALTER TABLE statement, that is also used to change the datatype of existing columns. Please check the video and the Scripts below to check and learn about both of these actions.
Please note: while adding a new column by using ALTER TABLE ADD statement the columns are always added at the end of the table. But if you want to add the column at a specific position use the Table Designer in SSSMS. Adding column in between is not recommended as it may do data movement by introducing an intermediate temporary table. Thus it is advised to add the columns at the end only and while Querying it you can use the specific column in the middle of the SELECT statement.
Check video on how to ADD and DROP columns in a Table:
–> SQL Script used in the above demo:
USE [Demo]
GO
-- create a sample table:
CREATE TABLE [dbo].[Employee](
[EmployeeID] int NOT NULL,
[EmployeeName] nvarchar(100) NOT NULL,
[Gender] nchar(1) NULL,
[DOB] datetime NULL,
[DOJ] datetime NULL,
[DeptID] int NULL
)
-- insert some sample/test records:
INSERT INTO [dbo].[Employee]
VALUES (1, 'MANOJ PANDEY', 'M', '1990-01-01', '2010-01-01', 101)
INSERT INTO [dbo].[Employee]
VALUES (2, 'JHON K', 'M', NULL, '2010-01-01', NULL)
INSERT INTO [dbo].[Employee] ([EmployeeID], [EmployeeName])
VALUES (3, 'Brock H')
GO
SELECT * FROM [dbo].[Employee]
GO
-- Add a new COLUMN:
ALTER TABLE [dbo].[Employee]
ADD MgrID INT
GO
SELECT * FROM [dbo].[Employee]
GO
-- Add column at specific location:
BEGIN TRANSACTION
GO
CREATE TABLE dbo.Tmp_Employee
(
EmployeeID int NOT NULL,
EmployeeName nvarchar(100) NOT NULL,
Gender nchar(1) NULL,
FathersName nvarchar(100) NULL,
DOB datetime NULL,
DOJ datetime NULL,
DeptID int NULL,
MgrID int NULL
) ON [PRIMARY]
GO
ALTER TABLE dbo.Tmp_Employee SET (LOCK_ESCALATION = TABLE)
GO
IF EXISTS(SELECT * FROM dbo.Employee)
EXEC('INSERT INTO dbo.Tmp_Employee (EmployeeID, EmployeeName, Gender, DOB, DOJ, DeptID, MgrID)
SELECT EmployeeID, EmployeeName, Gender, DOB, DOJ, DeptID, MgrID FROM dbo.Employee WITH (HOLDLOCK TABLOCKX)')
GO
DROP TABLE dbo.Employee
GO
EXECUTE sp_rename N'dbo.Tmp_Employee', N'Employee', 'OBJECT'
GO
COMMIT
SELECT EmployeeID, EmployeeName, Gender, MgrID, FathersName, DOB, DOJ, DeptID
FROM [dbo].[Employee]
GO
-- Drop an existing Column:
ALTER TABLE [dbo].[Employee]
DROP Column FathersName
GO
-- Adding Column with NOT NULL values
ALTER TABLE [dbo].[Employee]
ADD Address VARCHAR(100) NOT NULL
GO
-- error
/*
Msg 4901, Level 16, State 1, Line 38
ALTER TABLE only allows columns to be added that can contain nulls, or have a DEFAULT definition specified, or the column being added is an identity or timestamp column, or alternatively if none of the previous conditions are satisfied the table must be empty to allow addition of this column. Column 'Address' cannot be added to non-empty table 'Employee' because it does not satisfy these conditions.
*/
ALTER TABLE [dbo].[Employee]
ADD Address VARCHAR(100) NOT NULL DEFAULT ('N/A')
GO
SELECT * FROM [dbo].[Employee]
GO
ALTER TABLE [dbo].[Employee]
DROP COLUMN Address
GO
-- error
/*
Msg 5074, Level 16, State 1, Line 55
The object 'DF__Employee__Addres__xxxxxxxx' is dependent on column 'Address'.
Msg 4922, Level 16, State 9, Line 55
ALTER TABLE DROP COLUMN Address failed because one or more objects access this column.
*/
ALTER TABLE [dbo].[Employee]
DROP CONSTRAINT [DF__Employee__Addres__3C69FB99]
GO
ALTER TABLE [dbo].[Employee]
DROP COLUMN Address
GO
-- Final Cleanup
DROP TABLE [dbo].[Employee]
GO
Check my [next post] on how to Rename & change datatype of columns in a table.
SQL Basics – Create Database and Tables in SQL Server
A Database, it is a collection of data/information organized in a particular fashion so that it can be easily managed and accessed back in same fashion. The data stored and retrieved should in same format and should be consistent.
A Relational Database stores data in Tables, and there can be multiple tables in a database, which may be related to each other by referential integrity.
A Table is a collection of related data stored in a structured format within a database, in form or rows (tuple) and columns (fields).
–> Database:
Check video on how to create a new Database by using both, SSMS GUI and T-SQL Script:
–> T-SQL script to Create a new Database:
USE master GO CREATE DATABASE [Demo] ON PRIMARY ( NAME = N'Demo', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER2016\MSSQL\DATA\Demo.mdf' , SIZE = 4096KB , FILEGROWTH = 1024KB ) LOG ON ( NAME = N'Demo_log', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER2016\MSSQL\DATA\Demo_log.ldf' , SIZE = 1024KB , FILEGROWTH = 10% ) GO
–> Table:
Check video on how to create a new Table by using both, SSMS GUI and T-SQL Script:
–> T-SQL script to Create a new Table:
USE [Demo] GO CREATE TABLE [dbo].[Employee]( [EmployeeID] [int] NOT NULL, [EmployeeName] [nvarchar](100) NOT NULL, [Gender] [nchar](1) NULL, [DOB] [datetime] NULL, [DOJ] [datetime] NULL, [DeptID] [int] NULL ) SELECT * FROM [dbo].[Employee] INSERT INTO [dbo].[Employee] VALUES (1, 'MANOJ PANDEY', 'M', '1990-01-01', '2010-01-01', 101) sp_help 'Employee' -- ALT + F1 INSERT INTO [dbo].[Employee] VALUES (2, 'JHON K', 'M', NULL, '2010-01-01', NULL) INSERT INTO [dbo].[Employee] ([EmployeeID], [EmployeeName]) VALUES (3, 'Brock H') sp_rename 'Employees', 'Employee' DELETE FROM [dbo].[Employee] WHERE EmployeeID = 2 TRUNCATE TABLE [dbo].[Employee] DROP TABLE [dbo].[Employee]
Check my [next post] on how to ADD/DROP columns in a table.
MS SQL Server 2005 – New Feature | PIVOT and UNPIVOT
Using PIVOT and UNPIVOT Operator
You can use the PIVOT and UNPIVOT relational operators to manipulate a table-valued expression into another table. PIVOT rotates a table-valued expression by turning the unique values from one column in the expression into multiple columns in the output, and performs aggregations where necessary on any remaining column values that are desired in the final output. UNPIVOT performs the opposite operation to PIVOT by rotating columns of a table-valued expression into column values.
PIVOT provides syntax that is simpler and more readable than what may otherwise be specified in a complex series of SELECT…CASE statements.
A common scenario where PIVOT can be useful is when you want to generate cross-tabulation reports to summarize data. For example, suppose you want to query the PurchaseOrderHeader table in the AdventureWorks sample database to determine the number of purchase orders placed by certain employees. The following query provides this report, broken down by vendor:
USE AdventureWorks; GO SELECT VendorID, [164] AS Emp1, [198] AS Emp2, [223] AS Emp3, [231] AS Emp4, [233] AS Emp5 FROM (SELECT PurchaseOrderID, EmployeeID, VendorID FROM Purchasing.PurchaseOrderHeader) p PIVOT ( COUNT (PurchaseOrderID) FOR EmployeeID IN ( [164], [198], [223], [231], [233] ) ) AS pvt ORDER BY VendorID
Output:
VendorID Emp1 Emp2 Emp3 Emp4 Emp5
1 4 3 5 4 4
2 4 1 5 5 5
3 4 3 5 4 4
4 4 2 5 5 4
5 5 1 5 5 5
This means that the unique values returned by the EmployeeID column themselves become fields in the final result set. As a result, there is a column for each EmployeeID number specified in the pivot clause — in this case employees 164, 198, 223, 231, and 233. The PurchaseOrderID column serves as the value column, against which the columns returned in the final output, called the grouping columns, are grouped. In this case, the grouping columns are aggregated by the COUNT function. Note that a warning message appears indicating that any NULL values appearing in the PurchaseOrderID column were not considered when computing the COUNT for each employee.
UNPIVOT performs almost the reverse operation of PIVOT, by rotating columns into rows. Suppose the table produced in the example above is stored in the database as pvt, and you want to rotate the column identifiers Emp1, Emp2, Emp3, Emp4, and Emp5 into row values that correspond to a particular vendor. This means that you must identify two additional columns. The column that will contain the column values you are rotating (Emp1, Emp2,…) will be called Employee, and the column that will hold the values that currently reside under the columns being rotated will be called Orders. These columns correspond to the pivot_column and value_column, respectively, in the Transact-SQL definition. The query looks like this.
Create the table and insert values as portrayed in the above example:
CREATE TABLE pvt (VendorID int, Emp1 int, Emp2 int, Emp3 int, Emp4 int, Emp5 int) GO INSERT INTO pvt VALUES (1,4,3,5,4,4) INSERT INTO pvt VALUES (2,4,1,5,5,5) INSERT INTO pvt VALUES (3,4,3,5,4,4) INSERT INTO pvt VALUES (4,4,2,5,5,4) INSERT INTO pvt VALUES (5,5,1,5,5,5) GO --Unpivot the table. SELECT VendorID, Employee, Orders FROM (SELECT VendorID, Emp1, Emp2, Emp3, Emp4, Emp5 FROM pvt) p UNPIVOT (Orders FOR Employee IN (Emp1, Emp2, Emp3, Emp4, Emp5) )AS unpvt GO
Output:
VendorID Employee Orders
1 Emp1 4
1 Emp2 3
1 Emp3 5
1 Emp4 4
1 Emp5 4
2 Emp1 4
2 Emp2 1
2 Emp3 5
2 Emp4 5
2 Emp5 5
...
Note: UNPIVOT is not the exact reverse of PIVOT. PIVOT performs an aggregation and hence merges possible multiple rows into a single row in the output. UNPIVOT does not reproduce the original table-valued expression result because rows have been merged. Besides, NULL values in the input of UNPIVOT disappear in the output, whereas there may have been original NULL values in the input before the PIVOT operation.
Reference taken from MS BOL: http://msdn.microsoft.com/en-us/library/ms177410.aspx




