Friday, 21 February 2014

Index Fundamentals Part 1

Today I write a short introduction about Indexes in Microsoft SQL Server.

What exactly is an Index? An Index is a construct like a tree that is upside down to find datarows by indexed columns. There is a root level, a intermediate level and a leaf level or a heap if there is no clustered index. Let me explain with a worldwide phonebook.
The Root Page includes a pointer to the phonebook for every country the phonebook for each country is the intermediate Page and gets a pointer for every name into the leaf page (on a clustered index) or the heap.

In example for the query:

Select name, street phone from myphonebook where country = 'America' and Name = 'Adele, John'

The root page is called for Country = America and says goto leaf 1, on leaf 1 the page says
row with name 'Adele, John' is at pointer 4001 and leafpage or heap retrieves the row with
the query attributes.

On my next post I show the difference between nonclustered and clustered indexes.

Temporary Tables vs. Common Table Expression (CTE)

Today I want to show you how to use CTE and explain the difference
between CTE and a temporary tables.

Temporary Table
local temporary table
Local temporary tables (starting with a single #) are created in the tempdb and are only available in the current session. After closing the session the are dropped automatically.
global temporary table
Global temporary table (staring with two #) are created in the tempdb and are available in all sessions. They are automatically dropped after all user connections are closed.

CTE
CTE is not a table it is a temporary result set with scope on the current query, so it is not limited by the session it is limited by the current select.

Difference to a temporary table
CTE is a temporary result created in memory not in tempdb.
CTE cannot have an index.
CTE is only for the current statement.
CTE is faster (no table Creation)



Lets have a look at the execution plans
CTE (Subtreecost 0,313466)

local temp (Subtreecost 11,7748 for creating temptable + 0,313466 for select from temptable = 12,088266)



global temp (Subtreecost 11,7748 for creating temptable + 0,313466 for select from temptable = 12,088266)



As you can see CTE is not as expensive as temp tables but it can't be indexed and is pointed to current statement.
You should use CTE for inline subquerys or aggregating. For complex procedures or scripts you have to use temptables.

Copyable Version:
-- CTE
;With CTEResult(Itemno, itemname, Price)
AS
(
SELECT Itemno, itemname, Price from article a
)
SELECT * FROM CTEResult cr
WHERE cr.Itemno in (1,2,50)
ORDER BY cr.itemname
-- localtemptable
SELECT Itemno, itemname, Price into #localtemptable from article a
select * from #localtemptable where itemno in (1,2,50) order by Itemname
-- globaltemptable
SELECT Itemno, itemname, Price into ##globaltemptable from article a
select * from ##globaltemptable where itemno in (1,2,50) order by Itemname


drop table #localtemptable
drop table ##globaltemptable

Thursday, 20 February 2014

Logon Trigger to audit last Login

Now I will show you how to create a Logon Trigger on a Server
to safe the last login on a server for each user.

This script is useful searching no longer used Logins on a Server. 

Copyable Version:
USE [Login_Audit]

CREATE TABLE [dbo].[Login_Audit](
    [SID] [varbinary](85) NOT NULL,
    [Login] [sysname] NOT NULL,
    [User] [nvarchar](128) NULL,
    [Last_Login] [datetime] NULL
) ON [PRIMARY]

GRANT SELECT ON [dbo].[Login_Audit] TO [public]
GRANT UPDATE ON [dbo].[Login_Audit] TO [public]

INSERT INTO [dbo].[Login_Audit]
select [sid], name, NULL, NULL from sys.server_principals

CREATE TRIGGER [LogonTimeStamp]
ON ALL SERVER FOR LOGON
AS
BEGIN
update [Login_Audit].[dbo].[Login_Audit]
set        Last_Login = GETDATE(), [user] = user
where SID = suser_sid(SYSTEM_USER)
END

ENABLE TRIGGER [LogonTimeStamp] ON ALL SERVER


select *
from [Login_Audit].dbo.[Login_Audit]
where [LOGIN] = 'NT AUTHORITY\SYSTEM' -- use a own user here

-- Insert after Creating new Login
INSERT INTO [dbo].[Login_Audit]
select [sid], name, NULL, NULL
from sys.server_principals
where [sid] not in (select sid from [dbo].[Login_Audit])

Check the Rowsize of each Row

Today I show you a small script that outputs the rowsize for every row in a specified table.


This way you can check your rowsize and find extraordinary rowsizes in your tables.

Copyable Script:
/***** declares the variable for Tablename *****/
declare @t varchar(50)
/***** declares the variable for output ID *****/
declare @ID varchar(10)
/***** declares the variable for the command *****/
declare @sqlcmd varchar(max)

/***** sets variable for the table *****/
set @t = 'dbo.article'
/***** sets the variable for ID column in output *****/
set @ID = 'itemno'
/***** sets the variable for cmd *****/
set @sqlcmd =    'select ' + @ID +' , (0'
                select @sqlcmd = @sqlcmd + ' +case when isnull(len(' + name +
                '), 1) > isnull(datalength(' + name + '), 1) then isnull(len
                (' + name + '), 1) else isnull(datalength(' + name + '), 1) end '
                from syscolumns where id = object_id(@t)
set @sqlcmd =    @sqlcmd + ') as rowsize from ' + @t + ' (nolock) order by rowsize desc'
/**** Prints the execute cmd *****/
select @sqlcmd as Command
/**** Executes the cmd *****/
exec (@sqlcmd)

Tuesday, 18 February 2014

Cut off leading zeros on numbers in varchar field

Today we want to get rid of leading zeros in numbers on a varchar column.
To customize it you need to replace the ~ with a char that is not used in your column.
See my code below:



Copyable Version:
CREATE Table [dbo].[Leading_Zeros](
    [INT] [bigint] NULL,
    [Varchar] [varchar](250) NULL
    ) ON [PRIMARY]
   
GO

INSERT INTO [Leading_Zeros]
Values    (1, '001'),
        (2, 'Zero0000Zero'),
        (3, '156000748465'),
        (4, '000555000555000'),
        (5, 'TestString'),
        (6, 'Test00000String')
       
select    *,
        REPLACE(REPLACE(LTRIM(REPLACE(REPLACE([Varchar], ' ', '~'), '0', ' ')), ' ', '0'), '~', ' ') Leading_Zeros
from [Leading_Zeros]

Monday, 17 February 2014

Creating XML Data from Table

Today I need to create a xml field from a table. To show you how it works I just created a small 3 row example table.
Lets have a look at the Script:
First of all I created a table with 3 columns (ItemNo, Item_Name, Item_Price) and inserted 3 example rows.
After that I created the XML Table with columns (ID, Article)
A small while loop inserted the XML into the table.
In the End you will see the 3 items as XML and one Testitem as XML Select in Columns.

Copyable Version:
-- Create Source Table
CREATE TABLE [dbo].[article](
        [ItemNo] [bigint] NOT NULL,
        [Item_Name] [nvarchar](250) NOT NULL,
        [Item_Price] [money] NOT NULL
) ON [PRIMARY]
go
INSERT INTO [article]
Select 1, 'Testitem 1', 2.00
UNION ALL
Select 2, 'Testitem 2', 3.99
UNION ALL
Select 3, 'Testitem 3', 5.99
-- XML Table
CREATE TABLE [dbo].[Article_XML](
        [ID] [INT] PRIMARY KEY,
        Article XML
)  ON [PRIMARY]
GO
-- Insert into XML
DECLARE @counter INT = 1
DECLARE @row VARCHAR(MAX)
WHILE @counter <= 3
    BEGIN
        SET @row = (
                SELECT    ItemNo,
                        Item_Name,
                        Item_Price
                FROM article
                WHERE ItemNo = @counter
                FOR XML PATH ('Article')
                )
        INSERT Article_XML Values (@counter, @row)
        SET @counter += 1
    END
GO
-- Select all Fields
Select * from Article_XML
GO
-- Select XML Path
SELECT    Article.value('(/Article/ItemNo)[1]','varchar(50)') AS Artno,
        Article.value('(/Article/Item_Name)[1]','varchar(50)') AS item_name,
        Article.value('(/Article/Item_Price)[1]','money') AS price
From Article_XML
Where Article.exist('/Article[ItemNo=1]') = 1

The Hashbyte Function

Today I got a little problem with a developer that wants to use the Hashbyte function. After a little discussion and reading we saw that the output of the function ist varbinary so there is no way to put it into a varchar field without different results. See the Example:


So if you want to use the Hashbyte function you have to use the right data type.

Copyable Version:
DECLARE @HashThis nvarchar(40)
DECLARE @HashValue nvarchar(42)
DECLARE @HashValue2 varbinary(42)

set @HashThis = 'myteststring'
SELECT HASHBYTES('SHA1', @HashThis) as 'Auto data type'

set @HashValue=HASHBYTES('SHA1', @HashThis)
SELECT @HashValue as 'Varchar data type'

set @HashValue2=HASHBYTES('SHA1', @HashThis)
SELECT @HashValue2 as 'Varchar data type'