Pages

Saturday 22 September 2012

SQL SERVER - Different ways to know when was SQL Server restarted

Following are the ways to get the timestamp when SQL Server started:

Method 1: In SQL Server 2008 and above, with the DMV sys.dm_os_sys_info returns a column called sqlserver_start_time. This column contains the date and time SQL Server was last started:
SELECT sqlserver_start_time FROM sys.dm_os_sys_info 

Method 2:
SELECT start_time FROM sys.dm_exec_requests WHERE (session_id = 1) 

Method 3:
SELECT MIN(login_time) FROM sys.sysprocesses 

Method 4: TempDb is created every time SQL Server is started, so another workaround is to look at the creation date of the TempDb database:
SELECT create_date FROM sys.databases WHERE name = 'tempdb' 
OR
SELECT crdate FROM sysdatabases WHERE name='tempdb' 

Method 5:
SELECT start_time FROM sys.traces WHERE is_default = 1 

Method 6: Dashboard Reports
We can use the SQL Server Dashboard Report in SQL 2008 and above. Right click on the server name in SSMS and select Reports -> Server Reports -> Server Dashboard and you will get a report in which we can find Server Start Time.

Method 7: Windows Event Viewer
Windows Event Viewer is also an option to look for the start up time. If we open Windows Event Viewer and filter Event Sources for the SQL Server instance you can find all of the start up times that are still in the Event Viewer log.

Method 8: SQL Server Error Log
If you open the current SQL Server error log in SSMS under Management > SQL Server Logs and scroll to the bottom of the error log you can see when the server was started. Note the text "SQL Server is starting". You will want to look for this to make sure the error log was not cycled and give you a false impression of the start time. The error log method can be used for any version of SQL Server.
SP_ReadErrorLog 0,1,'Copyright (c)' 

Sunday 16 September 2012

SQL SERVER - Dynamic sorting using CASE statement

Let us look at the different examples to sort a field dynamically based on parameter supplied by the user in SQL Server. We can implement this by using dynamic SQL where we create a query on the fly and execute it, but dynamic SQL has many issues and very few advantages. If we are willing to limit ourselves to a fixed number of columns to sort then it is possible to achieve without dynamic SQL otherwise completely dynamic sorting by using several CASE statements will be the solution. We can write these types of queries using CASE statement with ORDER BY clause.

Following examples will demonstrate to use several CASE statements in ORDER BY to sort:

-- -- First, create a new database and a table to test
GO
CREATE DATABASE MyTestDB
GO

USE MyTestDB
GO
CREATE TABLE dbo.Employees (
EmployeeID INT IDENTITY(1,1),
EmployeeName VARCHAR(15),
Department VARCHAR(15),
Salary NUMERIC(16,2)
)

INSERT INTO dbo.Employees(EmployeeName, Department, Salary)
SELECT 'Barry','IT', 80000 UNION
SELECT 'Jones','IT', 40000 UNION
SELECT 'Billy','IT', 50000 UNION
SELECT 'Ralph','IT', 50000 UNION
SELECT 'Aaron','Finance', 40000 UNION
SELECT 'Barney','Finance', 25000 UNION
SELECT 'Callum','Finance', 25000 UNION
SELECT 'Oliver','Finance', 15000 UNION
SELECT 'Anderson','HR', 25000 UNION
SELECT 'Martin','HR', 15000 UNION
SELECT 'Garcia','HR', 15000 UNION
SELECT 'Caine','HR', 10000

Now create stored procedures to get sorted records from Employees table based on given field.

-- 1 -- Decide field to sort but without dynamic sort order.
CREATE PROCEDURE dbo.GetAllEmployees_1
(
@SortField VARCHAR(50) = 'EmployeeName'
)
AS
BEGIN

SELECT EmployeeName, Department, Salary
FROM dbo.Employees
ORDER BY
CASE
WHEN @SortField = 'EmployeeName' THEN EmployeeName
ELSE @SortField
END
ASC

END
GO

-- Execute the stored procedure created above:

EXEC dbo.GetAllEmployees_1 'EmployeeName'

-- 2 -- User option to sort on any field and sort in ascending or descending order method 1.
CREATE PROCEDURE dbo.GetAllEmployees_2
(
@SortField VARCHAR(50) = 'EmployeeName',
@SortDir VARCHAR(4) = 'ASC'
)
AS
BEGIN

SELECT EmployeeName, Department, Salary
FROM dbo.Employees
ORDER BY
CASE WHEN @SortField = 'EmployeeName' AND @SortDir = 'ASC' THEN EmployeeName END
ASC,
CASE WHEN @SortField = 'EmployeeName' AND @SortDir = 'DESC' THEN EmployeeName END
DESC,
CASE WHEN @SortField = 'Department' AND @SortDir = 'ASC' THEN Department END ASC,
CASE WHEN @SortField = 'Department' AND @SortDir = 'DESC' THEN Department END
DESC,
CASE WHEN @SortField = 'Salary' AND @SortDir = 'ASC' THEN Salary END ASC,
CASE WHEN @SortField = 'Salary' AND @SortDir = 'DESC' THEN Salary END DESC

END
GO

-- Execution of the following stored procedures will show the records sorted based on given field and based on given sort order:

EXEC dbo.GetAllEmployees_2 'EmployeeName', 'ASC'
EXEC dbo.GetAllEmployees_2 'EmployeeName', 'DESC'

-- 3 -- User option to sort on any field and sort in ascending or descending order method 2
CREATE PROCEDURE dbo.GetAllEmployees_3
(
@SortField VARCHAR(50) = 'EmployeeName',
@SortDir VARCHAR(4) = 'ASC'
)
AS
BEGIN

SELECT EmployeeName, Department, Salary
FROM dbo.Employees
ORDER BY
CASE WHEN @SortField = 'EmployeeName' AND @SortDir = 'ASC' THEN EmployeeName END
ASC,
CASE WHEN @SortField = 'EmployeeName' AND @SortDir = 'DESC' THEN EmployeeName END
DESC,
CASE WHEN @SortField = 'Department' AND @SortDir = 'ASC' THEN Department END ASC,
CASE WHEN @SortField = 'Department' AND @SortDir = 'DESC' THEN Department END
DESC,
CASE WHEN @SortField = 'Salary' AND @SortDir = 'ASC' THEN Salary END ASC,
CASE WHEN @SortField = 'Salary' AND @SortDir = 'DESC' THEN Salary END DESC

END
GO

-- Execute the following code to test the above created stored procedure:

EXEC dbo.GetAllEmployees_3 'EmployeeName', 'ASC'
EXEC dbo.GetAllEmployees_3 'EmployeeName', 'DESC'

Sometimes want to display records based on priority that also could done by dynamic sorting using CASE statement. In the following example we will sort the field Department based on priority where department “IT” should be first then “Finance” and then “HR”.

-- 4 -- Order by priority.
CREATE PROCEDURE dbo.GetAllEmployees_4
AS
BEGIN

SELECT EmployeeName, Department, Salary
FROM dbo.Employees
ORDER BY
CASE
WHEN Department = 'IT' THEN 1
WHEN Department = 'Finance' THEN 2
WHEN Department = 'HR' THEN 3
END ASC

END
GO

-- Execute the following code to test:
EXEC dbo.GetAllEmployees_4

In above example, the data type must be the same for sort field. In this example the data type is of integer. This can be helpful where in some situations we want display data based on priority.

Sunday 24 June 2012

SQL SERVER - Single DROP statement to drop multiple tables

We can drop multiple tables using a single DROP statement. For example, we have three tables Table1, Table2, Table3, we want to drop all these tables, and we can do it by following statement:
DROP TABLE Table1, Table2, Table3
Following is an example to drop multiple tables using single DROP statement:

CREATE DATABASE MyTestDB
GO

USE MyTestDB
GO

CREATE TABLE [dbo].[Table1](
[ID] INT IDENTITY(1,1) PRIMARY KEY,
[Column1] [varchar](6) NULL
) 
GO

CREATE TABLE [dbo].[Table2](
[ID] INT IDENTITY(1,1) PRIMARY KEY,
[Column2] [varchar](6) NULL
) 
GO

CREATE TABLE [dbo].[Table3](
[ID] INT IDENTITY(1,1) PRIMARY KEY,
[Column3] [varchar](6) NULL
) 
GO

We have created three tables above in database MyTestDB, now we can drop all three table by:
DROP TABLE Table1, Table2, Table3

-- Clean up 
USE MASTER
GO
DROP DATABASE MyTestDB

Saturday 2 June 2012

SQL SERVER - View Query Editor Window In Full Screen Mode

We can view query window in full screen mode by enabling Full Screen mode.It will hide all tool windows and view only document windows. Click anywhere in the Query Editor window to activate the window.

To enable Full Screen mode:

Press ALT + SHIFT + ENTER to toggle Full Screen mode.
OR
Go to View menu >> Select Full Screen Option

To disable Full Screen mode:
Press "Full Screen" button located at top in the menu bar.

By this way we can view SQL Server Management Studio in full screen mode.

Sunday 20 May 2012

SQL SERVER - Display Line Numbers In Query Editor Window

We can display line numbers in query editor window . Line numbers are useful for navigating code in SQL Server Management Studio

Go to menu Tools >> select Options >> Click Text Editor >> Click All Languages >> Click General. Select Line numbers in Display section.

To view line numbers in only some programming languages, select Line Numbers in the appropriate folder.

It should be noted that, document will not be printed with line numbers by turning on line numbering. For line numbers to print, we must select the Include Line Numbers check box in the Print command on the File menu.

Reference: Enabling Full Screen Mode

Saturday 12 May 2012

SQL SERVER - Add New Column In Existing Table With Default Value

Many times, we need to add new column in our existing database table. Many of us prefer to use a table designer to add new column, I would like to use SQL query to do this operation. If we add new column through designer it will not update the default value for that column and we need to update that column. With the help of following query, we can add new column to our existing table with default value we want to assign to that column without executing update statement.

ALTER TABLE [dbo].[Account]
ADD Active BIT DEFAULT 1 WITH VALUES;

Following is the complete example to test the above SQL statement.
USE [Master]
GO
CREATE DATABASE MyTestDB
GO

USE MyTestDB
GO
CREATE TABLE [dbo].[Account](
 [AccountID] INT IDENTITY(1,1) PRIMARY KEY,
 [AccountNumber] [varchar](6) NULL,
 [BranchName] [varchar](6) NULL,
 [Balance] [numeric](8, 2) NULL
) 
GO

INSERT INTO dbo.Account(AccountNumber,BranchName,Balance)
SELECT '000001','Br001',1202.00
UNION SELECT '000002','Br002',904.00

SELECT * FROM dbo.Account

ALTER TABLE [dbo].[Account]
ADD Active BIT DEFAULT 1 WITH VALUES;

SELECT * FROM dbo.Account

DROP TABLE [dbo].[Account]

USE MASTER
GO
DROP DATABASE MyTestDB

In above example, it will add a new column ‘Active’ with default value 1 for all the rows in table ‘[dbo].[Account]'. The above example shows that we can add new column in existing table with default value in SQL SERVER using ALTER TABLE statement.

Saturday 5 May 2012

SQL SERVER - View full content of a text or varchar(MAX) column

Recently I came across with a problem where I had to debug the dynamic SQL stored in large dynamic SQL varchar datatype variable and could not select in the result grid or print the whole SQL script because of SQL server limitation of displaying maximum number of text when dealing with large dynamic SQL variables.

Therefore, I started to search the web and found one tricky solution. Here I want to share that solution for such kind of problem.

DECLARE @str AS VARCHAR(MAX)
SELECT @str = REPLICATE(CAST('A' AS VARCHAR(MAX)), 65535)

SELECT [processing-instruction(X)] = @str 
FOR XML PATH(''),TYPE

This will convert the dynamic SQL to XML, instead of printing the dynamic SQL to the message tab. XML
The column name [processing-instruction(x)] sends special XML instruction allowing the text to be converted, along with any special characters. XML also keeps the formatting and can store up to 2 GB of data. It should be noted that whatever value you put in parenthesis would be incorporated in the XML tags, in this case “X”. We can strip of the XML tags from the top and bottom of the query text and go ahead with debugging.

Reference: Allow large text to be displayed in as a link