Showing posts with label Sql. Show all posts
Showing posts with label Sql. Show all posts

Tuesday, December 17, 2013

MS SQL Server Query to get Date difference of two dates in Days hours minutes and seconds

Hi in this post i will show how to get the date difference of two dates in DD:HH:MM:SS:MS format in MS Sql Server.

DD: Days
HH: Hours
MM: Minutes
SS: Seconds
MS: Milli Seconds

Sql Query :

SELECT *
,Days = datediff(dd, 0, DateDif)
,Hours = datepart(hour, DateDif)
,Minutes = datepart(minute, DateDif)
,Seconds = datepart(second, DateDif)
,MS = datepart(ms, DateDif)
FROM (
SELECT DateDif = EndDate - StartDate
,a.*
FROM (
SELECT StartDate = convert(DATETIME, '05-02-2013 01:10:00.000')
,EndDate = getdate()
) a
) Result

Output:


Tuesday, August 6, 2013

Check Data-length of the all the data in the column in Sql Server | query to check size of all the data present in the column


Taking an Example , Suppose we want to check the data-size of all the data present in a column for a Employee table :

Query :

SELECT DATALENGTH(CUSTOMER_ID) AS EMP_ID_LENGTH ,
       DATALENGTH(EMPLOYEE_NAME) AS EMPLOYEE_LENGTH,
       *
FROM EMPLOYEE_TABLE

Monday, August 5, 2013

changing column size in sql | Query to increase or decrease column length in sql server

Changing Column Size :

Suppose you want to change the size of a column having datatype as NVARCHAR of length 100.
We will increase it length to 200.

Query :

ALTER TABLE CUSTOMER_TABLE
ALTER COLUMN CUSTOMERNAME nvarchar(200)

Thursday, July 25, 2013

using cross apply in sql | Example for cross apply in sql | Switiching columns and rows

hi in this post i will show an example on how to use cross apply in sql.

Example :


CREATE TABLE #test (
 ID INT
 ,NAME VARCHAR(10)
 ,salary INT
 )

INSERT INTO #test
SELECT 1
 ,'chandan'
 ,100

SELECT *
FROM #test

SELECT A.COLUMN_NAME [Column_name]
 ,CASE 
  WHEN A.COLUMN_NAME = 'ID'
   THEN Convert(VARCHAR, T.ID)
  WHEN A.COLUMN_NAME = 'Name'
   THEN T.NAME
  WHEN A.COLUMN_NAME = 'Salary'
   THEN Convert(VARCHAR, T.salary)
  END [Value]
FROM tempdb.information_Schema.columns A
CROSS APPLY #test T
WHERE table_name LIKE '%#test%'



Monday, July 22, 2013

update table using from clause in a database | using from clause updating table records query example

Below is the query using from clause to update table records :

update Employee 
set Deptname = cc.Deptname
FROM Employee dd
inner join Department cc on  cc.DeptId = dd.DeptId
where dd.salary is not null



Wednesday, July 10, 2013

using OpenXML in sql server | Example of OpenXML in Sql Server | Reading XML Text using sp_xml_preparedocument

OpenXML in sql server is used to convert a XML Document in to a Sql table.

Below is the Example :

DECLARE @XMLDoc INT
DECLARE @xmlStr VARCHAR(1000)

SET @xmlStr = '<Root> <A><Name>James</Name><Mobile>123456</Mobile></A>
                      <A><Name>Rocky</Name><Mobile>789123</Mobile></A></Root>'

EXEC sp_xml_preparedocument @XMLDoc OUTPUT,
 @xmlStr

SELECT *
FROM OPENXML(@XMLDoc, '/Root/A', 2) WITH (
  NAME VARCHAR(10),
  Mobile VARCHAR(10)
  )

EXEC sp_xml_removedocument @XMLDoc



Output:


Monday, July 8, 2013

[Resolved] ALTER TABLE only allows columns to be added that can contain nulls, or have a DEFAULT definition specified..Column '' cannot be added to non-empty table '' because it does not satisfy these conditions. | Msg 4901, Level 16, State 1 | SQL alter table error

Hi in this post i will show how to resolve this below error.

Msg 4901, Level 16, State 1, Line 1
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 '' cannot be added to non-empty table '' because it does not satisfy these conditions.


1. Creating a scenario where you can get this type of issues.

create table empDetails
(
nameid int identity primary key,
name varchar(1000),
addres varchar(1000),
mobile numeric
)

insert into empDetails(name,addres,mobile) values ('chandan','india',123456789)

select * from empdetails



2. Now i will add a column to this table  

alter table empdetails
add [deptid] [int] NOT NULL 

Executing this wil give me the error as

To resolve this we will add default value '0' to the column.


Thus the error gets resolved.

Wednesday, July 3, 2013

using trigger how to track all the ddl event changes done in a database | Saving ddl events log in sql server database

hi in this post i will show, using trigger how to track all the dll changes like alter,create,drop etc in a database.

1. Creating a table which we will be using inside the trigger to save the ddl event log generated.

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [DDLAudit] (
 [eventtime] [varchar](50) NULL
 ,[EventType] [nvarchar](500) NULL
 ,[ServerName] [nvarchar](500) NULL
 ,[DatabaseName] [varchar](256) NULL
 ,[ObjectType] [varchar](256) NULL
 ,[ObjectName] [varchar](125) NULL
 ,[UserName] [varchar](200) NULL
 ,[CommandText] [varchar](max) NULL
 ,[XmlEvent] [xml] NOT NULL
 ,[modifiedby] [varchar](200) NULL
 ,[ModifiedOn] [datetime] NULL
 ) ON [PRIMARY]
GO

SET ANSI_PADDING OFF
GO


2. Creating trigger which will get executed for every ddl level changes and will save the event log in the DDLAudit Table.

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TRIGGER [DBAAudit_ALTER_Database] ON DATABASE
FOR DDL_DATABASE_LEVEL_EVENTS AS

BEGIN
 SET NOCOUNT ON

 DECLARE @ed XML

 SET @ed = EVENTDATA()

 INSERT INTO DDLAudit (
  eventtime
  ,EventType
  ,ServerName
  ,DatabaseName
  ,ObjectType
  ,ObjectName
  ,UserName
  ,CommandText
  ,[XmlEvent]
  ,modifiedby
  ,ModifiedOn
  )
 VALUES (
  convert(VARCHAR(50), getdate(), 109)
  ,@ed.value('(/EVENT_INSTANCE/EventType)[1]', 'nvarchar(500)')
  ,@ed.value('(/EVENT_INSTANCE/ServerName)[1]', 'nvarchar(500)')
  ,@ed.value('(/EVENT_INSTANCE/DatabaseName)[1]', 'varchar(256)')
  ,CONVERT(VARCHAR(125), @ed.query('data(/EVENT_INSTANCE/ObjectType)'))
  ,@ed.value('(/EVENT_INSTANCE/ObjectName)[1]', 'varchar(256)')
  ,suser_name()
  ,Cast(@ed.query('data(/EVENT_INSTANCE/TSQLCommand/CommandText)') AS NVARCHAR(max))
  ,@ed
  ,host_name()
  ,GetDate()
  )
END

SET NOCOUNT OFF
GO

SET ANSI_NULLS OFF
GO

SET QUOTED_IDENTIFIER OFF
GO

ENABLE TRIGGER [DBAAudit_ALTER_Database] ON DATABASE
GO


3. Result

Now to check alter or drop or create something in the database and then
execute this below select query to check for ddl event changes getting logged in the table.
 select * from [DDLAudit]


Sunday, June 30, 2013

using output parameters in sql server procedures | output parameter example in sql server

Hi in this post i will show how to use output parameter in sql stored procedures:

Example :

select * from employee


Now using this above we will create a stored procedure where we will make use of output parameter.

CREATE PROCEDURE getEmpDetails @empDeptId INT
 ,@Name VARCHAR(50) OUTPUT
 ,@salary NUMERIC(18) OUTPUT
AS
BEGIN
 SELECT @Name = EmpName
  ,@salary = Salary
 FROM employee
 WHERE EmpDeptID = @empDeptId
END
GO


Testing :

DECLARE @EID INT
 ,@EName VARCHAR(50)
 ,@ESal NUMERIC(18)

SET @EID = 3

EXEC getEmpDetails @empDeptId = @EID
 ,@Name = @EName OUTPUT
 ,@salary = @ESal OUTPUT

SELECT @EName AS 'First Name'
 ,@ESal AS 'Last Name'

PRINT @Ename
PRINT @ESal




use of @@identity,scope_identity() and IDENT_CURRENT('') in sql server | Example Difference of @@identity,scope_identity() and IDENT_CURRENT('')

Difference between @@identity,scope_identity() and IDENT_CURRENT('')

1. @@identity :

select @@identity will return the last identity value generated for any table.

Example :
Suppose we have a table and we are inserting data into that table. And a trigger gets executed when any insert operation is done for that table. Then Select @@identity will return the last identity value generated for the table inside the trigger.

2. scope_identity()

select scope_identity() will return the last identity value generated for a table which is executed in the same scope i.e stored procedure, function, insert query.

Example :
Suppose we have a table and we are inserting data into that table. And a trigger gets executed when any insert operation is done for that table. Select scope_identity() will return the last identity value generated for the table in which the data is being inserted and not for the table inside the trigger.

3. IDENT_CURRENT('')

return the last identity value generated for the specific table .

Example:

1. Select IDENT_CURRENT('Employee')
2. Select IDENT_CURRENT('Department')



Wednesday, June 19, 2013

Backup and restore database using a sql query in MS-SQL | Example of backup and restore of database in SQL

1. For backup use this below query

BACKUP DATABASE <Database_Name> TO DISK = 'D:\back\dbname.bak'

Make sure the folder has full rights in which we are going to save the .bak file or else you can get this below error:

Msg 3201, Level 16, State 1, Line 1
Cannot open backup device ''. Operating system error 5(Access is denied.).
Msg 3013, Level 16, State 1, Line 1
BACKUP DATABASE is terminating abnormally.


2. For Restoring a database use this below query 

Use MASTER 
GO
RESTORE DATABASE <Database_Name> FROM  DISK = N'D:\back\dbname.bak' WITH  FILE = 1,  KEEP_REPLICATION,  NOUNLOAD,  REPLACE,  STATS = 10
GO


Tuesday, June 18, 2013

check index fragmentation in sql server | Index Fragmentation Sql Query | Get Index Fragmentation Report

hi below is the code to get the fragmentation report in a database.

SELECT OBJECT_NAME(sindex.OBJECT_ID) AS TableName
,sindex.NAME AS CreatedIndexName
,ips.index_type_desc AS IndexType
,sindex.fill_factor AS Fill_Factor
,ips.fragment_count AS fragment_count
,ips.avg_fragmentation_in_percent
FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, NULL) ips
INNER JOIN sys.indexes sindex ON sindex.object_id = ips.object_id
AND sindex.index_id = ips.index_id
ORDER BY ips.avg_fragmentation_in_percent DESC


For fragmentation more than 30 use Rebuild Index and for fragmentation between 5 to 30 use Reorganize index.

Examples:
ALTER INDEX ALL ON NORTHWND.dbo.Customers
REORGANIZE ; 
GO

ALTER INDEX ALL ON NORTHWND.dbo.Customers
REBUILD;
GO

ALTER INDEX ALL ON NORTHWND.dbo.Customers
REBUILD WITH (FILLFACTOR = 80);
GO

Note:
1. Rebuilding index happens online and offline. During Offline the database resources gets locked.
2. Reorganizing index always happens online.

Saturday, June 1, 2013

Save images in Database using Sql Query | Using OPENROWSET save Images in sql server database

Below is the sql query to save images from disk into the database :


CREATE TABLE EmployeeDetails(EmpPhoto image)
INSERT INTO EmployeeDetails(EmpPhoto)
SELECT * FROM
OPENROWSET(BULK N'C:\Users\chandansingh\Desktop\download.jpg', SINGLE_BLOB) cs

Wednesday, May 22, 2013

[Resolved] SQL Error: Cannot schema bind view 'viewName' because name 'tableName' is invalid for schema binding. Names must be in two-part format and an object cannot reference itself.


Error Description:

Msg 4512, Level 16, State 3, Procedure EMPVIEW, Line 4
Cannot schema bind view 'DBO.EMPVIEW' because name 'EMPLOYEE' is invalid for schema binding. Names must be in two-part format and an object cannot reference itself.


Explanation: 
Such an Error occur when we create a view with schema binding and the table name we are using in it is without the schema name.

Add the schema name along with the table name in the script like tableName to dbo.tableName.
Hence it will resolve the error getting generated.

Example:

1
2

3


4

Monday, May 13, 2013

Creating Views with Scheme Binding in Sql Server

1. Lets create tables first which we will be using in the view. Here I'm using two tables employee and car.

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[Employee] (
 [EmpDeptID] [int] IDENTITY(1, 1) NOT NULL
 ,[EMpName] [varchar](100) NULL
 ,[salary] [numeric](18, 0) NULL
 ) ON [PRIMARY]
GO

SET ANSI_PADDING OFF
GO

SET IDENTITY_INSERT [dbo].[Employee] ON
GO

INSERT [dbo].[Employee] (
 [EmpDeptID]
 ,[EMpName]
 ,[salary]
 )
VALUES (
 1
 ,N'programming'
 ,CAST(1 AS NUMERIC(18, 0))
 )
GO

INSERT [dbo].[Employee] ([EmpDeptID],[EMpName],[salary])
VALUES (3,N'Mary',CAST(5000 AS NUMERIC(18, 0)))
GO

INSERT [dbo].[Employee] ([EmpDeptID],[EMpName],[salary])
VALUES (4,N'Anthony',CAST(500 AS NUMERIC(18, 0)))
GO

INSERT [dbo].[Employee] ([EmpDeptID],[EMpName],[salary])
VALUES (5,N'jacob1',CAST(555 AS NUMERIC(18, 0)))
GO

INSERT [dbo].[Employee] ([EmpDeptID],[EMpName],[salary])
VALUES (8,N'Peter',CAST(4500 AS NUMERIC(18, 0)))
GO

INSERT [dbo].[Employee] ([EmpDeptID],[EMpName],[salary])
VALUES (9,N'chandan',CAST(500 AS NUMERIC(18, 0)))
GO

SET IDENTITY_INSERT [dbo].[Employee] OFF
GO
--------------------------------------------------------
CREATE TABLE Car (carid INT,carname VARCHAR(100))
GO

INSERT INTO car
VALUES (1,'BMW')
GO

INSERT INTO car
VALUES (2,'FORD')
GO

INSERT INTO car
VALUES (3,'MAZDA')
GO

INSERT INTO car
VALUES (4,'Ferrari')
GO

2. Now I will create a Simple View without using scheme binding using this tables

CREATE VIEW [CARVIEW]
AS
SELECT *
FROM employee emp
INNER JOIN car c ON emp.empdeptid = c.carid

-------------------------------------------------------------------------
SELECT * FROM carview


3. Now Drop the table car and now run the view. The view gives error as the table car contained in it has been dropped now. Thus the view gets broken.






Hence to avoid such error we use View with scheme binding.
Thus it ensures the view created would not get broken in future and also would not allow any modifications to the tables it is using withing the view like renaming column name, delete column etc.

4. Recreate the Car table and now we will  Create view with scheme binding. After creating the view we will again try to drop the table car.


ALTER VIEW DBO.[CARVIEW]
 WITH SCHEMABINDING
AS
SELECT EMP.EMPDEPTID
 ,EMP.EMPNAME
 ,EMP.SALARY
 ,C.CARID
 ,C.CARNAME
FROM DBO.EMPLOYEE EMP
INNER JOIN DBO.CAR C ON EMP.EMPDEPTID = C.CARID

-----------------------------------------------
SELECT *
FROM DBO.[CARVIEW]



5. Now when we execute query to drop the table car it throws a exception that table cannot be dropped as it is referenced by one of the objects. Thus Views with Schema Binding would not get broken.



Monday, May 6, 2013

Find/Search keyword or text in all stored procedures in Sql Server Database

Suppose you want to check a table name wherever it has been used in the stored procedures of the database.

The Query to check this :


SELECT ROUTINE_NAME
 ,ROUTINE_DEFINITION
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_DEFINITION LIKE '%yourTextToBeSearched%'
 AND ROUTINE_TYPE = 'PROCEDURE'


Example: