Pages

Showing posts with label SQL. Show all posts
Showing posts with label SQL. Show all posts

Thursday, June 19, 2014

Transaction log backup job issue:

Currently the Transaction log backup job is stopped, because its giving performance issue. How i need to fix it..Let know any know this issue and How Fix it....

Tuesday, March 4, 2014

Set Incremental Number in sql

Set Incremental Number: DBCC CHECKIDENT('E.dbo.SubCategory', RESEED, 451) DBCC CHECKIDENT('E.dbo.Category', RESEED, 134) DBCC CHECKIDENT('E.dbo.SubCatDeptLink', RESEED, 480)

Friday, November 25, 2011

Convert Decimal to ROMAN using T-SQL

Do you want to convert a number into Roman Equivalent using T-SQL code or function? If yes then here you go:

/**************************************************
CREATED BY : Hari Sharma
PURPOSE    : Convert Decimal to ROMAN Equivalent
HOW TO USE : SELECT dbo.GetRomanNo(18)
             --OUTPUT: XVIII
**************************************************/
CREATE Function GetRomanNo(@N as varchar(20))
RETURNS VARCHAR(100)
AS
BEGIN
  DECLARE @s varchar(100), @r varchar(100),
          @i bigint, @p int, @d bigint
  SET @s = ''
  SET @r = 'IVXLCDM' -- Roman Symbols

  /* There is no roman symbol for 0, but I don't
   want to return an empty string */
  IF @n=0
     SET @s = '0'
  ELSE
  BEGIN
     SELECT @p = 1, @i = ABS(@n)
     WHILE(@p<=5)
     BEGIN
       SET @d = @i % 10
       SET @i = @i / 10
       SELECT @s = CASE
         WHEN @d IN (0,1,2,3) THEN
           Replicate(SubString(@r,@p,1),@d) + @s
         WHEN @d IN (4) THEN
           SubString(@r,@p,2) + @s
         WHEN @d IN (5,6,7,8) THEN
           SubString(@r,@p+1,1) +
           Replicate(SubString(@r,@p,1),@d-5) + @s
         WHEN @d IN (9) THEN
           SubString(@r,@p,1) + SubString(@r,@p+2,1) + @s
         END
       SET @p = @p + 2
     END
     SET @s = Replicate('M',@i) + @s
     IF @n < 0
     SET @s = '-' + @s
   END


   RETURN @s
END
GO

Track SQL Database Growth

In this article I am sharing a simple T-SQL code to track database growth for specific database. This could be a very simple query for SMEs but it can really help newbies:

/*************************************************
Purpose : Track Database Growth for a specific DB
Create By : Hari Sharma
**************************************************/
SELECT
   BackupDate =
   CONVERT(VARCHAR(10),backup_start_date, 111)
   ,SizeInMBs=FLOOR(backup_size/1024000)
FROM msdb..backupset
WHERE
   database_name = DB_NAME() --Specify DB Name
   AND type = 'd'
ORDER BY
   backup_start_date desc

Function to convert a string in Camel Case (Proper Case)

Sometime, we need to display string data in proper case, i.e. first character of each word should be in UPPER case. SQL Server doesn't provide any built-in function for this requirement. In this article, I am putting T-SQL code to create this function. This is a generalised Function that will return any input string in Proper Case [Camel Case]. Means Afetr every space, first later will be in UPPER case.


Example:
Input String    :  'microSoft sql server'
Output String : 'Microsoft Sql Server'
 
/*************************************************
CREATED BY : HARI SHARMA ON MAR 30, 2007
PURPOSE : TO CONVERT INPUT STRING IN CAMEL CASE
**************************************************/
CREATE FUNCTION [dbo].[CamelCase]
(@Str varchar(8000))
RETURNS varchar(8000) AS
BEGIN
  DECLARE @Result varchar(2000)
  SET @Str = LOWER(@Str) + ' '
  SET @Result = ''
  WHILE 1=1
  BEGIN
    IF PATINDEX('% %',@Str) = 0 BREAK
    SET @Result = @Result + UPPER(Left(@Str,1))+
    SubString  (@Str,2,CharIndex(' ',@Str)-1)
    SET @Str = SubString(@Str,
      CharIndex(' ',@Str)+1,Len(@Str))
  END
  SET @Result = Left(@Result,Len(@Result))
  RETURN @Result
END
---------------------------------------------------
-- HOW TO USE --
-- SELECT dbo.CamelCase('hARi nARAyan shARMa')
-- Output: Hari Narayan Sharma
---------------------------------------------------
GO

Function to Split Multi-valued Parameters

How to split a comma seperated value?
Many times we need to write T-SQL statements to split a comma seperated value, however string is not necessarily to be comma seperated, it can be seperated by any delimiter e.g. comma (,), @, &, ; etc.

How to use Multi-valued Parameters of SSRS report in a Stored procedures?
One more question comes around, how to use a multi valued parameter of SSRS report in a Stored Procedure to filter report data? I am sure you can't use a multi valued parameter directly in T-SQL code without spliting multiple values, if you do so without spliting values, SPROC will throw an error.

To find the answer of above questions, you create a user defined function using below T-SQL code:

/**********************************************
CREATED BY HARI
PURPOSE : To split any multivalued string
seperated by any delimiter into multiple rows
***********************************************/
CREATE FUNCTION [dbo].[SplitMultivaluedString]
(
   @DelimittedString [varchar](max),
   @Delimiter [varchar](1)
)
RETURNS @Table Table (Value [varchar](100))
BEGIN
   DECLARE @sTemp [varchar](max)
   SET @sTemp = ISNULL(@DelimittedString,'')
                + @Delimiter
   WHILE LEN(@sTemp) > 0
   BEGIN
      INSERT INTO @Table
      SELECT SubString(@sTemp,1,
             CharIndex(@Delimiter,@sTemp)-1)
     
      SET @sTemp = RIGHT(@sTemp,
        LEN(@sTemp)-CharIndex(@Delimiter,@sTemp))
   END
   RETURN
END
GO


/* How to use this function:
-----------------------------------------
SELECT * FROM [dbo].[SplitMultivaluedString] ('1,2,3,4', ',')
SELECT * FROM [dbo].[SplitMultivaluedString] ('1;2;3;4', ';')
SELECT * FROM [dbo].[SplitMultivaluedString] ('Hari#Thomas','#')
*/

Find Largest Size Tables in a Database

Below is the stored procedure to return largest tables of a database.

IF OBJECT_ID('sp_LargestTables' ,'P') IS NOT NULL
DROP PROC sp_LargestTables
GO
/***************************************************************
CREATE BY : Hari Sharma
PURPOSE : To get a list of tables according to their size.
***************************************************************/
CREATE PROC sp_LargestTables
(
   @n int = NULL,
   @IsSystemAllowed bit = 0
)
AS
BEGIN
   SET NOCOUNT ON
   DECLARE @LOW int
   SELECT @LOW = LOW
   FROM [master].[dbo].[spt_values] (NOLOCK)
   WHERE [number] = 1 AND [type] = 'E'

   IF @n > 0 SET ROWCOUNT @n
   SELECT TableName,[Row Count],[Size (KB)] FROM
   (
      SELECT QUOTENAME(USER_NAME(o.uid)) + '.' +
                     QUOTENAME(OBJECT_NAME(i.id))
         AS TableName
         ,SUM(i.rowcnt) [Row Count]
         ,CONVERT(numeric(15,2),
            (((CONVERT(numeric(15,2),SUM(i.reserved)) * @LOW) / 1024.0))) AS [Size (KB)]
      FROM sysindexes i (NOLOCK)
      INNER JOIN sysobjects o (NOLOCK)
         ON i.id = o.id AND
         ((@IsSystemAllowed = 1 AND o.type IN ('U', 'S')) OR o.type = 'U')
      WHERE indid IN (0, 1, 255)
      GROUP BY
         QUOTENAME(USER_NAME(o.uid)) + '.' +
         QUOTENAME(OBJECT_NAME(i.id))
   ) AS Z
   ORDER BY [Size (KB)] DESC

   SET ROWCOUNT 0
END
GO


How to use:

1. If you want all the user tables in the database with largest db size then:
EXEC sp_LargestTables [No Need to pass parameters]

2. If you want only 3 tables in the database with largest db size then:
EXEC sp_LargestTables 3

3. If you want only 20 tables in the database with largest db size including system tables then:
EXEC sp_LargestTables 20,1

Count Number of Rows for Tables of a Database

Easiest way to get an exact value of Number of Rows for all the tables in a SQL Server database

1. Use DBCC UPDATEUSAGE - this updates the values of rows for each partition in a table.
2. Use undocumented stored procedure sp_msForEachTable and store the result set in a table.

Below is the query to get required output:

USE [DatabaseName]
GO

DECLARE @DynSQL NVARCHAR(255)
SET @DynSQL = 'DBCC UPDATEUSAGE (' + DB_NAME() + ')'
EXEC(@DynSQL)

IF OBJECT_ID('tempdb..#T','U') IS NOT NULL
DROP TABLE #T
GO

CREATE TABLE #T (TableName nvarchar(500),NumberOfRows int)
GO

INSERT INTO #T
EXEC sp_msForEachTable 'SELECT PARSENAME(''?'', 1) as TableName,COUNT(*) as NumberOfRows FROM ?'
GO 
SELECT * FROM #T ORDER BY NumberOfRows DESC

T-SQL Puzzle 1: WHERE & GROUP BY

What will be the output of query given below. There is no FROM clause and no GROUP BY clause.

Does it throw an error?
Do you get any resultset?
Do you get a single row containing NULL?
Do you get a single row with 'Something' data?
Do you get multiple rows?
Cheers!


SELECT 'Something'
WHERE 1=2
HAVING 1=1

Note: You can easily check your answer by running the query but please check your skills before you do so. 

T-SQL Puzzle 2 - CASE Statement

What will be the output of below Query:

DECLARE @f as int

SET @f = 1
SELECT CASE 1
    WHEN @f THEN 'First'
    WHEN @f THEN 'Second'
    ELSE 'Nothing' END
AS CaseStmt

Below are the options:
1. First
2. Second
3. Nothing
4. No records
5. syntax Error

T-SQL Puzzle 3 - Syntax Behaviour

What will be the out of below SELECT statements:

SELECT 1.Columns
SELECT 1.ColumnName
SELECT (1.)ColumnName
SELECT '1.'ColumnName
SELECT 1.#ColumnName
SELECT $1.ColumnName
SELECT 1.[ a%^& .ColumnName]

Has anyone seen this behavior?
Do you have any idea what's happening?

T-SQL Puzzle 4 - Can we rollback after TRUNCATE?

You know that TRUNCATE is DDL command and we can't rollback DDL commands as per BOL.
So what will be the output of below query:

CREATE TABLE Test(Col int)
GO

INSERT INTO Test (Col)
VALUES (1), (2), (3)

SELECT * FROM Test

BEGIN TRAN
   TRUNCATE TABLE Test
   SELECT * FROM Test
ROLLBACK TRAN
SELECT * FROM Test

DROP TABLE Test

Thursday, November 24, 2011

mcts self paced training kit exam 70 536

Some part Help :
http://findebookee.com/e/exam-70-448

Resouces For Sql Server:Install adventureworks Database

The VS.net 2008 Beta 2 was released one month ago. After downloading the virtual machine, I decided to install the AdventureWorks sample database on the SQL Express. The main reason to choose SQL Express is because the VS 2008 Beta2 virtual machine already installed SQL Express. Here is a list of steps I followed to install Adventure Works databases.
  1. Check SQL Express and ensure it’s up and running.
    Open a DOS prompt, and type net start “SQL Server (SQLExpress)”. If you get warning message, “the requested service has already been started”, then the SQL Express is running.

     
  2. Configure/verify SQL Express to accept remote connections
    3.1 Enable TCP/IP
    By default, the TCP/IP and Named Pipes protocols are disabled.

    Launch the SQL Server Configuration Manager from SQL Server 2005 | Configuration Tools | SQL Server Configuration Manager

    Click SQL Server 2005 Network Configuration | Protocols for SQL Express, right click TCP/IP and enable it.

    3.2 Enable SQL Browser service. If you don’t enable this service, you need to specify the TCP port in your connection string.

    Administrative Tools | Services | SQL Server Browser

    3.3 In the DOS prompt, type sqlcmd -S .\SQLExpress, if you get “>” sign, cool! It works.

    3.4 type “select @@version”, then enter, type “go”, then enter, you should see the result message which indicates that you can connect to your SQL Express without issues now.
  3. Download and install Adventure Works database
    Browse to http://www.codeplex.com/MSFTDBProdSamples/Release/ProjectReleases.aspx?ReleaseId=4004 and click AdventureWorksDB.msi
    Once the download is completed, you can start to install it by following the installation screen instruction. The database files will be installed at c:\Program files\microsoft sql server\mssql.1\mssql\data folder. The installation just places the database files in this folder, you still to attach it into the SQL Express.
  4. Attach database.
    Once connect to the SQL Express, type the following commands:

      USE [master]

    GO

    CREATE DATABASE [AdventureWorks] ON

    ( FILENAME = N’C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\AdventureWorks_Data.mdf’ ),

    ( FILENAME = N’C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\AdventureWorks_Log.ldf’ )

    FOR ATTACH ;

    GO

     
  5. You can verify database by typing the following commands:

     select name from sys.databases
    Go


    If you see the AdventureWorks in the list, then database is attached successfully.


    Alternatively, you can verify the AdventureWorks database by launching VS 2008 beta 2, then click View | Server Explore, right click on the Data Connections, then click Add connection. In the Choose Data Source window, choose SQL Server, then click Next. In the Add Connection window, enter .\SQLExpress as the Server name. Select the database name, AdventureWorks. Click Test Connection.