Friday 12 December 2014

SQL - How to capture multiple identities from INSERT INTO SELECT

-- Example Source table
CREATE TABLE #SourceTable ( Contact CHAR(30) );

INSERT #SourceTable VALUES ( 'User1' )
INSERT #SourceTable VALUES ( 'User2' )
INSERT #SourceTable VALUES ( 'User3' )

-- Example Dest table
CREATE TABLE #ImportedUsers ( Id       INT IDENTITY(1, 1) NOT NULL
,                             UserName CHAR(30) );

-- Imported users + new ID table
DECLARE @IDs TABLE ( Id       INT
,                    UserName CHAR(30) )

INSERT #ImportedUsers
 OUTPUT inserted.Id
 ,      inserted.UserName
 INTO @IDs ( Id
 ,           UserName )
SELECT DISTINCT Contact
FROM #SourceTable

SELECT *
FROM @IDs

Monday 29 September 2014

Time Your Code Using StopWatch

Here's a useful snippet for timing how long a piece of code takes to execute, and so can be useful for identifying bottlenecks.
using System;
using System.Diagnostics;
using System.Threading;
class Program
{
    static void Main(string[] args)
    {
        Stopwatch stopWatch = new Stopwatch();
        stopWatch.Start();

        // Code you want to measure goes here.. lets just sleep for the purpose of this example
        Thread.Sleep(10000);

        stopWatch.Stop();
        // Get the elapsed time as a TimeSpan value.
        TimeSpan ts = stopWatch.Elapsed;

        // Format and display the TimeSpan value into something meaningful
        string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
            ts.Hours, ts.Minutes, ts.Seconds,
            ts.Milliseconds / 10);
        Console.WriteLine("RunTime " + elapsedTime);
    }
}