Feeds:
Posts
Comments
This is the Sample query to get the last executed time for a stoed procedure.
Method 1:

--With Text:
SELECT object_name(qp.objectid) Object_Name , OBJECT_DEFINITION(qp.objectid) Defination, qs.sql_handle,qs.statement_start_offset,qs.statement_end_offset,
qs.creation_time,qs.last_execution_time,qp.dbid
FROM   sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st
CROSS APPLY sys.dm_exec_text_query_plan(qs.plan_handle, DEFAULT, DEFAULT) AS qp
INNER JOIN SYS.procedures S ON QP.objectid = S.object_id
WHERE  st.text like '%S_POP%'

Method 2:

SELECT db_name(database_id) DatabaseName, object_name(object_id) ObjectName, *
FROM   sys.dm_exec_procedure_stats
WHERE  database_id = DB_ID()
ORDER BY database_id

I have modified table using design mode and tried to save the table.

A pop up Warning message box appear with following error message.

Saving changes is not permitted. The changes you have made require the following tables to be dropped and re-created. You have either made changes to a table that can’t be re-created or enabled the option Prevent saving changes that require the table to be re-created.

Prevent Saving Changes Error Message

Solution:

Go to Tools menu select option.

Expand Designers => Table and Database Designers

Uncheck the Check box for Prevent Saving changes that require table re-creation.

Click on OK button to save the changes.

Prevent Saving Changes Solution

Reference Link:
Reference

When am working with SQL Server 2012, I found Ctrl+R is not working, which is for show & hide the Result Pane.

How to Assign Ctrl+R To show & Hide Result Pane?

Go to Menu => Tools => Options

1) Expand Environment => Keyboard

2) Right side panel , we can see Show commands containingbelow text box type Window.ShowResultsPane .

3) In the below drop down (Shortcuts for selected command) Select SQL Query Editor.

4) In the below drop down (Use new shortcut in:)  Select SQL Query Editor.

5) Keep mouse cursor in Press Shortcut keys: Text box and Press Ctrl+R.

6) Click Assign Button to Assign the key for Show Result Pane.

7) Click OK Button to completed the process.

From the next Query window, We can use Ctrl+R for Show & Hide Result Pane.

Below Image will give the clear information.

Assigning Shortcut Key Ctrl+R In SQL Server 2012

SSRS

SQL SELECT INTO Statement

SQL SELECT INTO Statement will create a backup of existed table.

Syntax:

SELECT	<COLUMN NAMES>
INTO	<NEW TABLE NAME>
FROM	<OLD TABLE NAME>
WHERE	<CONDITIONS>

Example 1:

USE AdventureWorks
GO

SELECT *
INTO dbo.Address_Backup
FROM Person.Address
GO

The above statement will create a backup table for Person.Address table with the name of Address_Backupin dbo schema.

Example 2:

SELECT *
INTO Tbl_Backup
FROM (
		SELECT 1 ID,'Gustavo' NAME UNION ALL
		SELECT 2 ,'Kim'UNION ALL
		SELECT 3 ,'Michael'UNION ALL
		SELECT 4 ,'Benjamin'
	 ) AS Tbl

In the above example, we are going to create a table with the name of Tbl_Backup .But the resulted values are not from a UDT. After executing the query, if we check out the Tbl_Backup Design/Properties (Alt+F1), we can observe ID data type is INT and NAME data type is VARCHAR (8).

Why the Name Data type is Varchar (8)?

In the result set Max length of NAME column is 8. (‘Benjamin’)

Means SQL Server consider the Max length of the column as Data type length.

Example 3:

IF OBJECT_ID('EmpDetails') IS NOT NULL DROP TABLE EmpDetails
GO

IF OBJECT_ID('EmpDetails_Bak') IS NOT NULL DROP TABLE EmpDetails_Bak
GO

Create Table EmpDetails(ID Int IDENTITY, Name Varchar(100), HRA MONEY,[BASIC] MONEY, SAL AS HRA+BASIC, HDate DATETIME NOT NULL DEFAULT GETDATE())
GO

INSERT INTO EmpDetails(Name, HRA ,BASIC)
VALUES ('Gustavo', 4500 , 9000 )
	  ,('Kim', 5000 , 10000 )
	  ,('Michael', 4000 , 8000 )
GO

SELECT *
INTO EmpDetails_Bak
FROM EmpDetails
GO

SELECT * FROM EmpDetails_Bak
GO

In the above example,

Column Name EmpDetails EmpDetails_Bak
ID Identity Identity
Name Varchar(100) Varchar(100)
HRA Money Money
BASIC Money Money
SAL Money(Computed Column) Money
HDate DateTime(Default getdate()) Datetime

The table EmpDetails_Bak structure is differs from EmpDetails as shown in the above list.

It means, when we using SELECT INTO statement, the backup table won’t get the same structure as Main table.

Example 4:


IF OBJECT_ID('EmpDetails')IS NOT NULL DROP TABLE EmpDetails
GO

IF OBJECT_ID('tempdb..#EmpDetails_OPClause') IS NOT NULL
DROP TABLE #EmpDetails_OPClause
GO

IF OBJECT_ID('tempdb..#EmpDetails_OPClauseUpdate') IS NOT NULL
DROP TABLE #EmpDetails_OPClauseUpdate
GO

Create Table EmpDetails(ID Int IDENTITY, Name Varchar(100), HRA MONEY,BASIC MONEY, SAL AS HRA+BASIC, HDate DATETIME NOT NULL DEFAULT GETDATE())
GO

Create Table #EmpDetails_OPClause(ID Int, Name Varchar(100), HRA MONEY,BASIC MONEY, SAL MONEY, HDate DATETIME)
GO

Create Table #EmpDetails_OPClauseUpdate(ID Int, OldName Varchar(100),NewName Varchar(100))
GO

--0.01

INSERT INTO EmpDetails(Name, HRA ,BASIC)
OUTPUT inserted.*
INTO #EmpDetails_OPClause
VALUES ('Gustavo', 4500 , 9000 )
	  ,('Kim', 5000 , 10000 )
	  ,('Michael', 4000 , 8000 )
GO

select * from #EmpDetails_OPClause
GO

Update EmpDetails
Set Name ='Michael J'
OUTPUT inserted.ID ID , deleted.Name 'OldName', inserted.Name 'NewName'
INTO #EmpDetails_OPClauseUpdate
WHERE ID = 3
GO

SELECT*FROM #EmpDetails_OPClauseUpdate
GO

In this example, we are using INTO statement for OUTPUT Clause.

We are inserting the inserted records into #EmpDetails_OPClause table. (0.01)

Here we are inserting old value and New value into #EmpDetails_OPClauseUpdate table.

–Cleaning Tables

DROP TABLE Address_Backup , Tbl_Backup,EmpDetails ,EmpDetails_Bak

Notes:

  • New table name should not exist in the database. . Otherwise it will thorugh the following error message.

Msg 2714, Level 16, State 6, Line 1 There is already an object named ‘EmpDetails_Bak’ in the database.

  • Select statement should have the column names. Otherwise it will through the following error message.

Msg 1038, Level 15,State 5, Line 1 An object or column name is missing or empty. For SELECT INTO statements, verify each column has a name. For other statements, look for empty alias names. Aliases defined as “” or [] are not allowed. Change the alias to a valid name.

There are 4 Types of Rank functions in SQL Server.
Row_Number() : Row Number will return serial numbers in the result set.
Rank() : Rank will returns the rank of each row , if the values are same for more records it will give the same number,if the value is change, then it will give the row number in the partition.
Dense_Rank() : Dense_Rank will returns the rank of each row,if the values are same, then it will give the same number,if the value is changed ,then it will give the next number of the previous row in the partition.
Ntile(n) : It will partition the result set into “n” numbers and give the rank to each record.
Script:
--Declare a table with name of @CLASSROOM
DECLARE @CLASSROOM TABLE (ID INT IDENTITY, NAME VARCHAR(100) , BRANCH VARCHAR(10) , M1 INT , M2 INT , M3 INT , TOT as (M1+M2+M3) )

--Insert values into @CLASSROOM
INSERT INTO @CLASSROOM
VALUES	 ( 'RAJ' ,'CSE' , 60 , 70 , 40 )
		,( 'RAHUL' ,'CSE' , 60 , 80 , 30 )
		,( 'RAMESH' ,'CSE' , 60 , 60 , 40 )
		,( 'RAKESH' ,'IT' , 50 , 70 , 60 )
		,( 'RAM' ,'IT' , 50 , 70 , 60 )
		,( 'RAVI' ,'IT' , 60 , 70 , 90 )
		,( 'RAJESH' ,'IT' , 70 , 30 , 80 )
		,( 'ROHITH' ,'CSE' , 50 , 60 , 90 )
		,( 'ROCK' ,'IT' , 50 , 70 , 50 )
		,( 'RAAGHAV' ,'CSE' , 50 , 60 , 60 )

--Ranking functions
SELECT	 NAME , TOT
		,ROW_NUMBER() OVER(ORDER BY TOT DESC) [Row_Number]
		,RANK() OVER(ORDER BY TOT DESC) [Rank]
		,DENSE_RANK() OVER( ORDER BY TOT DESC) [Dense_Rank]
		,NTILE(2) OVER(ORDER BY TOT DESC) [Ntile]
FROM @CLASSROOM

Result:
Windows Functions MysqlBag

Script:

--Ranking functions With Partition By clause.
SELECT	 BRANCH,NAME , TOT
		,ROW_NUMBER() OVER(PARTITION BY BRANCH ORDER BY TOT DESC) [Row_Number]
		,RANK() OVER(PARTITION BY BRANCH ORDER BY TOT DESC) [Rank]
		,DENSE_RANK() OVER(PARTITION BY BRANCH ORDER BY TOT DESC) [Dense_Rank]
		,NTILE(2) OVER(PARTITION BY BRANCH ORDER BY TOT DESC) [Ntile]
FROM @CLASSROOM
Result:

Here we can see different methods to separate Integers and String data types from a string variable.

SET NOCOUNT ON

declare @str varchar(100) = 'A1B2C3D4'
DECLARE @I INT = 1,@var varchar(100)='' , @int Varchar(100) = ''

WHILE @I <= LEN(@str)
begin
-- 48 Is ASCII Key for '0' and 57 is for '9'
--Checking Each char is between 0 to 9 or not. If yes then concatenation to @int variable. Else concatenation with @var Variable.
IF @I = 1 SELECT @str 'Input String' , SUBSTRING(@STR,@I,1) 'First Char of the Input String', ASCII(SUBSTRING(@STR,@I,1))  AS 'ASCII Value of the First Char'

IF ASCII(SUBSTRING(@STR,@I,1)) BETWEEN 48 AND 57
--IF PATINDEX('[^0-9-]',SUBSTRING(@STR,@I,1) ) = 0
BEGIN
IF @I = 1 SELECT @str , SUBSTRING(@STR,@I,1), ASCII(SUBSTRING(@STR,@I,1))
SET @int += SUBSTRING(@STR,@I,1)+','
END
ELSE
BEGIN
SET @var += SUBSTRING(@STR,@I,1)+','
END
set @I +=1
end
SELECT @str 'Input String','Integers'= SUBSTRING(@int,1,LEN(@int)-1) , REVERSE(STUFF(REVERSE(@var),1,1,'')) AS [String]
---------------------------Method 2----------------------------
/*
Inserting each character into @TBL table.
Using with CASE Statement displaying and Checking CHAR is Integer or String.
*/
SELECT @I = LEN(@Str)
DECLARE @TBL TABLE (ID INT IDENTITY , [Char] CHAR(1))
WHILE @I >= 1
begin
INSERT INTO @TBL SELECT SUBSTRING(@STR,@I,1)
set @I -=1
end

SELECT [Char],CASE WHEN PATINDEX('%[^0-9-]%',  [Char] ) = 0 THEN 'Integer' ELSE 'Strings' END AS [TYPE]
FROM @TBL
ORDER BY    [TYPE], ID  DESC
--------------------------------Method 3-------------------
SELECT Integers , Strings  FROM
(
SELECT ID, [Char],CASE WHEN PATINDEX('%[^0-9-]%',  [Char] ) = 0 THEN 'Integers' ELSE 'Strings' END AS [TYPE]
FROM @TBL
)  AS P
PIVOT(MAX(CHAR) FOR [TYPE] IN (Integers,Strings)  ) AS PVT
ORDER BY Integers  , Strings

How to insert Identity value in a table?
/*
In the below example we have single Identity column table. Using with "Default Values" we can insert the values into table.
*/
create table #tbl(id int identity)
go

insert into #tbl default values
go 10

select * from #tbl
go

drop table #tbl
go

____________________________________________________________________________________________
CREATE TABLE #TBL1(ID INT IDENTITY , NAME VARCHAR(10) NULL , COUNTRY VARCHAR(10) DEFAULT 'INDIA')
go

INSERT INTO #TBL1 DEFAULT VALUES
GO 10

SELECT * FROM #TBL1
go

drop table #TBL1
go

/*
Here the ID is Identity column , Name will allow the nulls and Country Default value is 'India'.
*/

Follow

Get every new post delivered to your Inbox.