Friday, October 4, 2013

Extract Query Result in A Flat File (BCP command)

Please consider following script given below.

EXEC sp_configure 'show advanced options',1;
RECONFIGURE;

EXEC sp_configure 'Ad Hoc Distributed Queries',1;
RECONFIGURE;

EXEC sp_configure 'xp_cmdshell','1'
RECONFIGURE;
DECLARE @CMD VARCHAR(500) = 'BCP "SELECT col1, col2 FROM [MY_DB].[DBO].[MY_TABLE]" queryout C:\TestData.txt -t, -c -S' + @@ServerName+ ' -U user1 -P pwd@123 -T';


EXEC xp_cmdshell @CMD

Monday, August 12, 2013

Find Dependency of an Object in SQL Server.

If we want to know dependency of Object in MSSQL it is very easy to find out by using following query.
It is very useful because of if we want to modify/delete any object like Function/Procedure then it is necessary to know where actually it is used.

USE TEST_DB
SELECT * FROM SYS.DM_SQL_REFERENCING_ENTITIES ('DBO.MY_FUNCTION', 'OBJECT');




Thursday, May 16, 2013

Sequence in SQL Server 2012

A sequence is a user-defined object which is use to generate a sequence of numeric value based on specified value at the time of declaration. Sequence can generate ascending or descending numeric values at a specified interval and can be recycle (restart). Sequence is independent object that’s why it is not dependent on any table unlike IDENTITY. Sequence is much faster in generating number compared to IDENTITY.


--Creating a sequence
CREATE SEQUENCE [DBO].[seq_mySequence]
AS [BIGINT]
START WITH 1
INCREMENT BY 1
MINVALUE 1
MAXVALUE 999
GO

--Generating sequence
SELECT NEXT VALUE FOR [DBO].[seq_mySequence] AS Seq
GO



----Alter or Reset sequence----
ALTER SEQUENCE [DBO].[seq_mySequence]
RESTART WITH 101
INCREMENT BY 1
MINVALUE 101
MAXVALUE 999
GO

--Calling sequence----
SELECT NEXT VALUE FOR [DBO].[seq_mySequence] AS Seq
GO