Category: Uncategorized

  • Script to update the dates on AdventureWorks database

    In case you ever needed this:

    IF OBJECT_ID('tempdb..#GeneratedScripts') IS NOT NULL DROP TABLE #GeneratedScripts;
    CREATE TABLE #GeneratedScripts (Id INT IDENTITY(1,1), SqlScript NVARCHAR(MAX));
    -- 1. Setup global ceiling
    INSERT INTO #GeneratedScripts (SqlScript) VALUES ('DECLARE @TargetCeiling DATETIME = GETDATE();');
    DECLARE @SchemaName NVARCHAR(256), @TableName NVARCHAR(256), @AnchorColumn NVARCHAR(256);
    DECLARE @Sql NVARCHAR(MAX), @ColumnUpdates NVARCHAR(MAX);
    DECLARE tbl_cursor CURSOR FOR
    SELECT DISTINCT SCHEMA_NAME(t.schema_id), t.name
    FROM sys.tables t
    JOIN sys.columns c ON t.object_id = c.object_id
    JOIN sys.types y ON c.user_type_id = y.user_type_id
    WHERE y.name IN ('datetime', 'datetime2')
    AND t.is_ms_shipped = 0
    AND t.temporal_type <> 1;
    OPEN tbl_cursor;
    FETCH NEXT FROM tbl_cursor INTO @SchemaName, @TableName;
    WHILE @@FETCH_STATUS = 0
    BEGIN
    -- Pick Anchor Column
    SET @AnchorColumn = NULL;
    SELECT TOP 1 @AnchorColumn = c.name FROM sys.columns c JOIN sys.types y ON c.user_type_id = y.user_type_id
    WHERE c.object_id = OBJECT_ID('[' + @SchemaName + '].[' + @TableName + ']') AND y.name IN ('datetime', 'datetime2')
    ORDER BY CASE WHEN c.name = 'ModifiedDate' THEN 0 ELSE 1 END;
    SET @ColumnUpdates = '';
    SELECT @ColumnUpdates = @ColumnUpdates + '[' + c.name + '] = DATEADD(DAY, src.DayDiff, [' + c.name + ']), '
    FROM sys.columns c JOIN sys.types y ON c.user_type_id = y.user_type_id
    WHERE c.object_id = OBJECT_ID('[' + @SchemaName + '].[' + @TableName + ']')
    AND y.name IN ('datetime', 'datetime2') AND c.is_computed = 0 AND c.generated_always_type = 0;
    IF LEN(@ColumnUpdates) > 0
    BEGIN
    SET @ColumnUpdates = LEFT(@ColumnUpdates, LEN(@ColumnUpdates) - 1);
    -- Logic: Disable triggers for this table, update, then re-enable triggers.
    -- This fixes Msg 4083 / Trigger conflict issues.
    SET @Sql = '
    ALTER TABLE [' + @SchemaName + '].[' + @TableName + '] DISABLE TRIGGER ALL;
    UPDATE t SET ' + @ColumnUpdates + '
    FROM [' + @SchemaName + '].[' + @TableName + '] AS t
    CROSS JOIN (SELECT DATEDIFF(DAY, MAX([' + @AnchorColumn + ']), @TargetCeiling) AS DayDiff FROM [' + @SchemaName + '].[' + @TableName + ']) AS src
    WHERE src.DayDiff > 0;
    ALTER TABLE [' + @SchemaName + '].[' + @TableName + '] ENABLE TRIGGER ALL;' ;
    INSERT INTO #GeneratedScripts (SqlScript) VALUES (@Sql);
    END
    FETCH NEXT FROM tbl_cursor INTO @SchemaName, @TableName;
    END
    CLOSE tbl_cursor; DEALLOCATE tbl_cursor;
    -- Output the results
    SELECT SqlScript FROM #GeneratedScripts ORDER BY Id;

    What it does, in short: sets a ceiling (of today, including hour, minutes, seconds, milliseconds). It searches for all the user tables (well, it excludes historical and replicated ones) that have a column of DATETIME/DATETIME2() data types (except for the columns used for historical tables, computed columns) and brings them to as close to today as possible).
    Of course it can be improved, well aware of that.
    Can be used on other databases, so give it a try.
    That’s it.

  • An error occurred within the report server database. This may be due to a connection failure, timeout or low disk condition within the database – when migrating SSRS databases to a new server

    You have restored your databases, you renamed them if needed (in my case ReportServer and ReportServerTempDB from ReportServer$Instance and ReportServer$InstanceTempDB), jobs, everything, when migrating SSRS to a new server. Yet, scheduled subscriptions still not working (oddly enough, ad-hoc ones were working, could browse reports, etc.). In my case, when I tried editing Subscriptions, I hit this error: An error occurred within the report server database. This may be due to a connection failure, timeout or low disk condition within the database. In my particular case, I checked the logs at \Program Files\Microsoft SQL Server Reporting Services\SSRS\LogFiles and found this error burried in the logs: Microsoft.ReportingServices.Diagnostics.Utilities.ReportServerStorageException: An error occurred within the report server database. This may be due to a connection failure, timeout or low disk condition within the database. ---> Microsoft.Data.SqlClient.SqlException: Invalid object name 'ReportServer$InstanceTempDB.dbo.ExecutionCache‘ – in other words, something is still trying to use the old database names.

    Blind try:
    SELECT OBJECT_NAME(id) FROM syscomments
    WHERE text LIKE '%ReportServer$InstanceTempDB%'

    Result: Schedule_UpdateExpiration. Turns out there is a trigger on the ReportServer - dbo.Schedule table that runs the following code:
    UPDATE
    EC
    SET
    AbsoluteExpiration = I.NextRunTime
    FROM
    [ReportServerTempDB$Instance].dbo.ExecutionCache AS EC
    INNER JOIN ReportSchedule AS RS ON EC.ReportID = RS.ReportID
    INNER JOIN inserted AS I ON RS.ScheduleID = I.ScheduleID AND RS.ReportAction = 3

    Once I replaced the hard-coded old database name with the new database name (ReportServerTempDB), it started working.

    Again, this is a very quick blog post, but to summarize:

    • ad-hoc reports were working
    • scheduled reports were not working
    • tried to edit a schedule from the /Reports/manage in the web browser – failed with the above error
    • changed the hard-coded value in the trigger, everything started working again.

  • Wierd tuning trick with dynamic SQL when encountering unmatched indexes

    Later edit: Both Uwe Ricken (https://www.linkedin.com/in/uwericken/, https://www.db-berater.de/) and Sascha Lorenz (https://www.linkedin.com/in/saschalorenz/) correctly pointed out that my little inconsisted writing was a tad too inconsistent – first of all, the title itself was NOT highlighting the very point of this blog post: unmatched indexes and how to deal with them by using dynamic SQL. Truth be told, nor was the content.
    Thank you for reaching out and helping me in rethinking the idea.

    First things first:
    This blog post is NOT about how SQL uses estimates or density vector, it is simply about the idea of unmatched indexes (very few people seem to know about it, myself included) and playing with it.

    A very quick (and most likely inconsistent writing) one, from a customer perf tuning investigation. Consider the following scenario:

    A table with columns from Column1 to Column8.
    Column1 is INT with IDENTITY property, Column8 is a BIT and we care about the 0 values, not the 1 (we are looking for customers who are not yet processed), Column2 and Column3 are NVARCHAR(MAX), while the rest of the columns are INT data types.
    Yes, table autogenerated with ORM, I am so not going there…

    Anyways:

    DECLARE @Indexed BIT = 0;
    SELECT column1,
           column2,
           column3,
           column4,
           column5,
           column6,
           column7
    FROM [dbo].[Changes]
    WHERE column8 = @Indexed;

    It is a known issue, I will not go into much detail, but NVARCHAR(MAX) is not your best bet for defining a data type to hold strings (if you are not familiar with the issues: https://sqlundercover.com/2025/06/30/why-not-just-use-varcharmax/).

    How about the actual IO performed?

    LE1: Also, by looking at the execution plan:

    By hovering the mouse over the SELECT statement, no actual warning message was displayed, so we need to dig deeper into the XML plan:

    End of LE1.

    Enter unmatched indexes (https://www.brentozar.com/blitzcache/unmatched-indexes/).

    LE2: I created a filtered index:

    CREATE INDEX IX_Change_includes
    ON dbo.Changes
    (
    column7,
    column6,
    column5, 
    column4
    )
    INCLUDE (column2, column3)
    WHERE column8 = 0

    End of LE2.

    I will rewrite the SQL query to use dynamic SQL:

    DECLARE @SQLString NVARCHAR(MAX);
    DECLARE @ParamDefinition NVARCHAR(500);
    DECLARE @Indexed BIT = 0;
    
    SET @SQLString = N'
    SELECT column1,
           column2,
           column3,
           column4,
           column5,
           column6,
           column7
    FROM [dbo].[Changes]
    WHERE column8 = @IndexedValue;';
    
    SET @ParamDefinition = N'@IndexedValue BIT';
    
    EXECUTE sp_executesql @SQLString,
                          @ParamDefinition,
                          @IndexedValue = @Indexed;

    Yes, you can write dynamic SQL in many ways, I know that.

    LE3: For this particular scenario (dynamic SQL with a filtered index), it did not seem to help.

    Does not look like our index was selected. It only managed to paralelize the query, but nothing more.

    End of LE3.

    LE4: I moved the original index definition from the original post to this position, to reflect that initally the query was tested with a filtered index, and now we are testing with an index with included columns and no filter.

    End of LE4.

    Now let us define an index that should help us out:

    CREATE INDEX IX_Change_includes
    ON dbo.Changes
    (
    column8,
    column7,
    column6,
    column5, 
    column4
    )
    INCLUDE (column2, column3)

    We had to include columns 2 and 3 because they are NVARCHAR(MAX), so you cannot simply put them in the index definition.

    Having said that, let us see the execution plan now, as well as the IO for the dynamic SQL with our index with included columns:

    Absurdly fast compared to our regular SQL query.

    LE5:

    • please note that while the original post only highlighted one index (included columns, no filter). The expanded post also includes the test with a filtered index
    • DBCC FREE PROCCACHE and DBCC DROPCLEANBUFFERS were run after every change introduced, which did not help in this particular scenario
    • WITH RECOMPILE was not allowed in this particular scenario, nor stored procedures, so these scenarios have not been tested.

    Again, thank you everyone who reached out to help me correct my initial post – indeed was way too confusing and did not reach its intended purpose.

  • Stop using variables in stored procedures for no reason

    Yes, writing about SQL Server every 10 years will not bring me any medals. I know, I know.
    Anyway, I am currently checking what is what on a new project and I got to see this in the header of a stored procedure from 10 years ago: “use @variable to suppress 'parameter sniffing‘”.
    I will NOT dwelve here in the parameter sniffing topic, there are a ton of good resources out there already, but let’s have a little repro of the issue we are introducing by using variables inside stored procedures.

    Before moving on, run the following in the AdventureWorks database:

    CREATE NONCLUSTERED INDEX test
    ON [Sales].SalesOrderHeader
    INCLUDE ([TotalDue])

    Now, let’s run some SELECT statements. Make sure you include the actual execution plan.

    SELECT
    CASE
    WHEN SalesPersonID IS NULL THEN 'Internet Sales'
    ELSE CAST(SalesPersonID AS VARCHAR(10))
    END AS SalesPerson,
    SUM(TotalDue) AS TotalSalesAmount
    FROM
    Sales.SalesOrderHeader
    WHERE
    SalesPersonID = 279
    GROUP BY
    CASE
    WHEN SalesPersonID IS NULL THEN 'Internet Sales'
    ELSE CAST(SalesPersonID AS VARCHAR(10))
    END
    ORDER BY
    TotalSalesAmount DESC;

    If you also applied the index, you will see that both estimated and actual number of rows are bang on.

    Let’s repeat the experiment, but let’s declare a variable.

    DECLARE @SalesPersonId INT = 279;
    SELECT
    CASE
    WHEN SalesPersonID IS NULL THEN 'No Sales Person'
    ELSE CAST(SalesPersonID AS VARCHAR(10))
    END AS SalesPerson,
    SUM(TotalDue) AS TotalSalesAmount
    FROM
    Sales.SalesOrderHeader
    WHERE
    SalesPersonID = @SalesPersonId OR (@SalesPersonId IS NULL AND SalesPersonID IS NULL)
    GROUP BY
    CASE
    WHEN SalesPersonID IS NULL THEN 'No Sales Person'
    ELSE CAST(SalesPersonID AS VARCHAR(10))
    END
    ORDER BY
    TotalSalesAmount DESC;

    Any changes in the execution plan? You bet – now, the actual and estimated number of rows are not quite there.

    By now, the savy reader will know what happens when we put this inside a stored procedure:

    CREATE PROCEDURE GetSalesBySalesPerson @SId INT = NULL -- Input parameter, defaults to NULL
    AS
    BEGIN
        -- SET NOCOUNT ON added to prevent extra result sets from
        -- interfering with SELECT statements.
        SET NOCOUNT ON;
    
        DECLARE @SalesPersonId INT = @SId; -- Assign the parameter to the variable
    
        SELECT CASE
                   WHEN SalesPersonID IS NULL THEN
                       'No Sales Person'
                   ELSE
                       CAST(SalesPersonID AS VARCHAR(10))
               END AS SalesPerson,
               SUM(TotalDue) AS TotalSalesAmount
        FROM Sales.SalesOrderHeader
        WHERE SalesPersonID = @SalesPersonId
              OR
              (
                  @SalesPersonId IS NULL
                  AND SalesPersonID IS NULL
              )
        GROUP BY CASE
                     WHEN SalesPersonID IS NULL THEN
                         'No Sales Person'
                     ELSE
                         CAST(SalesPersonID AS VARCHAR(10))
                 END
        ORDER BY TotalSalesAmount DESC;
    END;
    GO
    EXEC GetSalesBySalesPerson @SId = 279;

    We just moved our issue inside a stored procedure, but nothing more.

    Look, I am not saying there is no time or place for variables, but this is not it. Remember the comment from 10 years ago I found in the procedure header?
    I cannot show you the code, but I can show you what happened after I removed the variables.

    I will let you guess which is what.
    List for you: variables, stored procedures, parameter sniffing, density vector.

  • Collecting blocking chain

    We’ve all been there, trying to figure out who’s blocking who, who is the most avid blocker. Personally, I was and still am a huge fan of Adam Machanic’s (b) sp_WhoIsActive for accomplishing that. But I stumbled upon a nice script from @SQL_Undercover (b|t) which is using sp_BlitzWho stored procedure.

    For the ones not familiar with the Blitz family, you don’t know what you’re missing. I strongly encourage you to get familiar with them, they’re simply awesome.

    Back to the blocking chain topic… The original script looked thru data that was already collected. This is awesome when you want to look at what happened in the past. But when your server is on fire, you want to see the blocking chain, like right now.

    So, I took the original script, added a few more parameters, converted it to a dynamic TSQL, and voila…

    create or alter proc BlitzBlockingChain
    (	@now bit = 0,							/* show what's the blocking chain now rather then in the past */
    	@startdate as datetime = null,		
    	@enddate as datetime = null,
    	@blitzwho_table as nvarchar(128) = N'dbatools.dbo.BlitzWho',
    	@execute bit = 0,						/* execute the statement or just show it */
    	@minutes_back int = 60					/* how far back to go when @now = 0 */
    )
    as
    begin
    	set nocount on;
    
    	declare @tsql nvarchar(4000);
    	declare @tbl nvarchar(128) = N'blocking_chain_now_' + cast(@@spid as nvarchar(5))
    
    	/* check if the table exists */
    	if @now = 0 and object_id(@blitzwho_table) is null
    	begin
    		raiserror('Specified BlitzWho table (%s) does not exists.', 16, 1, @blitzwho_table) with nowait;
    		return;
    	end;
    
    	/* check what happened in the past 2 hrs */
    	if @now = 0
    	begin
    		if @startdate is null
    			select @startdate = dateadd(minute, 0-@minutes_back, getdate());
     
    		if @enddate is null
    			select @enddate = dateadd(minute, @minutes_back, @startdate);
    	end;
    
    	if @now = 1
    	begin
    		/* make sure we do get the correct snapshot, not mixed with some old data */
    		set @tsql = N'drop table if exists tempdb.dbo.' + @tbl;
    		exec(@tsql);
    
    		/* get the data */
    		exec sp_BlitzWho @OutputDatabaseName = 'tempdb', @outputschemaname = 'dbo', @outputtableName = @tbl;
    	end
    
    	/* tsql template to use */
    	set @tsql = N'
    ;WITH BlockChain 
    (       Chain,
    		ID, 
    		CheckDate, 
    		session_id,
    		blocking_session_id, 
    		login_name,
    		host_name, 
    		program_name, 
    		database_name, 
    		elapsed_time,
    		query_text, 
    		status, 
    		wait_info)
    as
    (	select  cast(''Lead Blocker: '' + cast(BlitzWho.[session_id] as varchar) as varchar(50)) as [chain],
    		BlitzWho.ID, 
    		BlitzWho.CheckDate, 
    		BlitzWho.session_id,
    		BlitzWho.blocking_session_id, 
    		BlitzWho.login_name, 
    		BlitzWho.host_name, 
    		BlitzWho.program_name, 
    		BlitzWho.database_name, 
    		BlitzWho.elapsed_time,
    		BlitzWho.query_text, 
    		BlitzWho.status, 
    		BlitzWho.wait_info
    	from ##TABLE## BlitzWho
    	where [blocking_session_id] is null
    	and exists (select 1 from ##TABLE## BW where BlitzWho.[CheckDate] = BW.[CheckDate] and BlitzWho.[session_id] = BW.[blocking_session_id])
    	##WHERE_DATES##
    
    	union all
     
    	select  cast(BlockChain.[Chain] + '' -> '' + cast(BlitzWho.[session_id] as varchar) as varchar(50)) as [chain],
    		BlitzWho.ID, 
    		BlitzWho.CheckDate, 
    		BlitzWho.session_id,
    		BlitzWho.blocking_session_id, 
    		BlitzWho.login_name, 
    		BlitzWho.host_name, 
    		BlitzWho.program_name, 
    		BlitzWho.database_name, 
    		BlitzWho.elapsed_time,
    		BlitzWho.query_text, 
    		BlitzWho.status, 
    		BlitzWho.wait_info
    	from ##TABLE## BlitzWho
    	inner join BlockChain on BlitzWho.[CheckDate] = BlockChain.[CheckDate] AND BlitzWho.[blocking_session_id] = BlockChain.[session_id]
    )
    select * from blockchain
    order by [checkdate], [database_name], [chain]';
    
    	/* replace all tokens */
    	set @tsql = replace(@tsql, '##WHERE_DATES##', iif(@now=1, N'', N'AND BlitzWho.[CheckDate] BETWEEN @StartDate AND @EndDate'));
    	set @tsql = replace(@tsql, '##TABLE##', iif(@now = 1, N'tempdb.dbo.' + @tbl, @blitzwho_table));
    
    	/* execute the statement */
    	if @execute = 1
    	begin
    		if @now = 0
    			exec sp_executesql @stmt = @tsql, @params = N'@StartDate datetime, @EndDate datetime', @StartDate = @startDate, @endDate = @endDate;
    		if @now = 1 
    			exec sp_executesql @stmt = @tsql;
    	end
    	/* do not execute - show the generated tsql */
    	if @execute = 0
    		select cast('<?q-- ' + @tsql + ' --?>' as xml) as [tsql];
    
    	/* Cleanup */
    	if @now = 1
    	begin
    		set @tsql = N'drop table if exists tempdb.dbo.' + @tbl;
    		exec(@tsql);
    	end
    end
    go
    

    I hope I do not missed anything in the code, I tested it to the best of my abilities but I am still human.

    Of course, please test it on a non-production instance first 🙂

  • Change the PowerBI desktop default language

    For whatever reason, I ended up with Romanian as the default language for PowerBI desktop (no regional settings, no browser settings, no nothing would provide a hint to the installer that it should install and set the app to Romanian).
    This did not help either: https://community.powerbi.com/t5/Service/change-PowerBI-language-menus-to-english-while-maintaining/td-p/4782

    I ended up in C:\Program Files\Microsoft Power BI Desktop\bin, where there were to folders: ro and en. I renamed the ro folder to something else (aaa – I know, I’m a genius) and presto, I was back to English.

    Hope this helps.

    And yes, I will start blogging again, soon enough, so watch out for this space.

    Best regards,
    io

  • Remove TDE completely. Really?

    I must be getting old, two blog posts in the same year! 🙂

    Anyway, I made some additional testing as part of a TDE (Transparent Data Encryption, that is) implementation and I noticed couple of interesting things when you want to remove the TDE completely from the server:

    • When checking sys.databases, tempdb is shown as not encrypted (is_encrypted = 0, not 1, as one would expect).
      You will get the correct status, though, under sys.dm_database_encryption_keys.
    • A simple right-click and restart service would not work in this case. One must stop and then start the SQL Server service in order for the TDE to be completely removed

    As a side note, I’m on SQL Server 2012 SP2, did not find the time to check other versions.

    How to remove TDE, you might wonder? Well, the lovely guys at simple-talk have the answer for you, I’m not going to repeat it here.

    Best regards,
    io

  • To OR or …?

    Yeap, a year later, there we go, posting a quick blog again.

    A colleague of mine skyped me about a query that was running slow. Well, slow means that it ran for 90 seconds, and then it timed out, that is.

    Here is the little repro of the challenge:

    
    USE [AdventureWorks2012]
    GO
    
    SET ANSI_NULLS ON
    GO
    
    SET QUOTED_IDENTIFIER ON
    GO
    
    CREATE TABLE [dbo].[test](
    [ProductID] [INT] NOT NULL,
    [FirstDescription] [INT] NULL,
    [SecondDescription] [INT] NULL,
    CONSTRAINT [PK_ProductID_test] PRIMARY KEY CLUSTERED
    (
    [ProductID] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    
    GO
    
    

    I know, I’m too lazy NOT to generate the table from SSMS :-).

    Moving further, generate some data for the table – I’m regularly using SQL Data Generator. Again, lazy-lazy, I know…

    Now, moving on to the actual code:

    
    DBCC FREEPROCCACHE
    DBCC DROPCLEANBUFFERS
    
    SET STATISTICS IO, TIME ON
    
    SELECT *
    FROM [dbo].[test]
    WHERE [FirstDescription] = 299002250 -- your own value here
    OR FirstDescription IS NULL
    AND SecondDescription = 84830679 -- your own value here;
    
    

    I made sure I had a cold cache, then I simply selected all columns where the first description column has a particular value, or the first description column is NULL and the second column has a particular value.

    Nothing magic here.

    And the results from statistics and time being set to ON:

    
    SQL Server parse and compile time:
    CPU time = 0 ms, elapsed time = 0 ms.
    
    SQL Server Execution Times:
    CPU time = 0 ms, elapsed time = 0 ms.
    SQL Server parse and compile time:
    CPU time = 0 ms, elapsed time = 2 ms.
    
    SQL Server Execution Times:
    CPU time = 0 ms, elapsed time = 0 ms.
    
    (2 row(s) affected)
    Table 'test'. Scan count 2, logical reads 6, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
    
    (1 row(s) affected)
    
    SQL Server Execution Times:
    CPU time = 0 ms, elapsed time = 35 ms.
    SQL Server parse and compile time:
    CPU time = 0 ms, elapsed time = 0 ms.
    
    SQL Server Execution Times:
    CPU time = 0 ms, elapsed time = 0 ms.
    
    

    And now for the fun part, the execution plan:

    execution plan 1

    So we’re seeking the same index twice AND also “helping” it with a very expensive sort? Well, a picture worth a thousand words, right?

    Any other way to re-write the query? How about:

    
    SELECT *
    FROM [dbo].[test]
    WHERE [FirstDescription] = 299002250
    UNION ALL
    SELECT *
    FROM [dbo].[test]
    WHERE FirstDescription IS NULL
    AND SecondDescription = 84830679;
    
    

    So we replaced the OR with UNION ALL. I will spare you all the details, but I will show you the new execution plan:

    execution plan 2

    So we got rid of the expensive sort! How cool is that!

    As a closing remark, I urge you to understand that this worked in this particular scenario. To clear the fog: if you are trying the same trick with multiple ORs and UNIONs on the same column, the result will favor the OR:

    
    SELECT *
    FROM [dbo].[test]
    WHERE [FirstDescription] = 299002250
    OR FirstDescription = 1684182851
    OR FirstDescription = 364563112;
    
    SELECT *
    FROM [dbo].[test]
    WHERE [FirstDescription] = 299002250
    UNION ALL
    SELECT *
    FROM [dbo].[test]
    WHERE FirstDescription = 1684182851
    UNION ALL
    SELECT *
    FROM [dbo].[test]
    WHERE FirstDescription = 364563112;
    
    

    The execution plans, side by side:

    execution plan 3

    Of course, I barely scratched the surface here. Please feel free to do your own testing and let the rest of us know the results.

    Best regards,
    io

     

  • DATETIME and its surprises

    Well, it’s about time I write another blog post (with a promise that I’ll do it more than once a year).

    I’m going to start a series of “bad habits to kick” as for me it is important that we all have a common ground on SQL Programming.

    1.            Consider the following scenario:

    SET

    LANGUAGE British;

    SELECT
    CAST(’02/12/2007′
    AS
    DATETIME);

    SET
    LANGUAGE us_english;

    SELECT
    CAST(’02/12/2007′
    AS
    DATETIME);

    SET
    LANGUAGE British;

    SELECT
    CAST(‘2007-02-12’
    AS
    DATETIME);

    SET
    LANGUAGE us_english;

    SELECT
    CAST(‘2007-02-12’
    AS
    DATETIME);

    SET
    LANGUAGE British;

    SELECT
    CAST(‘20070212’
    AS
    DATETIME);

    SET
    LANGUAGE us_english;

    SELECT
    CAST(‘20070212’
    AS
    DATETIME);

    And let’s see the results:

    Changed language setting to British.

    ———————–

    2007-12-02 00:00:00.000

    (1 row(s) affected)

    Changed language setting to us_english.

    ———————–

    2007-02-12 00:00:00.000

    (1 row(s) affected)

    Changed language setting to British.

    ———————–

    2007-12-02 00:00:00.000

    (1 row(s) affected)

    Changed language setting to us_english.

    ———————–

    2007-02-12 00:00:00.000

    (1 row(s) affected)

    Changed language setting to British.

    ———————–

    2007-02-12 00:00:00.000

    (1 row(s) affected)

    Changed language setting to us_english.

    ———————–

    2007-02-12 00:00:00.000

    (1 row(s) affected)

    So the first two results are different, while the last query returns the same result! What’s going on?

    It has to do with the way Microsoft implemented the date and time data types, starting with SQL Server 2008.

    We have two similar data types, DATETIME and DATETIME2. What people fail to realize is that the two data types behave completely differently (Use the time, date, datetime2 and datetimeoffset data types for new work. These types align with the SQL Standard. They are more portable. time, datetime2 and datetimeoffset provide more seconds precision. datetimeoffset provides time zone support for globally deployed applications – see here.)

    DATETIME preserves the old, non-standard ANSI  settings, in order to be backwards compatible, while DATETIME2 is pretty much standard compatible.

    2.           How can we address this issue?

    The answer lies in the code itself (repeated here for clarity):

    SET
    LANGUAGE British;

    SELECT
    CAST(‘20070212’
    AS
    DATETIME);

    SET
    LANGUAGE us_english;

    SELECT
    CAST(‘20070212’
    AS
    DATETIME);

    This will return the same date and time; and the reason lies (again) in Books Online, for CAST and CONVERT:

    For date and time styles, we have:

    12

    112

    ISO

    12 = yymmdd

    112 = yyyymmdd

    In other words, even if DATETIME is not ISO standard, the way we input data for CAST can be aligned with the ISO standard, thus having the correct results each time.

    I hope this helps.

  • Say What? – “Management Studio: must be set in single thread apartment (STA) mode before OLE calls can be made”

    Yes, I have another couple of minutes to document this weird message.

    I was trying to access the database properties for one of our databases. Guess what: I couldn’t as there was no owner! Well, the easiest thing to do is to alter the authorization on the database; as you may have guessed it already, I didn’t pay any kind of attention to the error message, and quickly jumped to the magic world of… creating a diagram (actually the mouse pointer was in the wrong location, I just clicked, so it was not my fault, right?). Well, this time I got to do a print screen:

    OK, now let’s copy that stupid message without reading it, select some random text from it, and do a blind search in hope for sheer luck. Click the Copy sign… and there you go, another weird stuff:

    Now this one finally got my attention.

    It turns out that it used to be a bug (check here), but it was supposed to be fixed. Well, apparently not all the cases were covered.

    My wild guess is that:

    If you have a database that does not have an owner (how about someone who left the company and we removed the user account – I need to check this) and you want to create a diagram, you will see the first pop-up error message. Trying to copy the message itself (via the Copy feature – yeap, those little sheets of paper in the lower-left corner) will yield the second error.

    Of course, the solution is the most difficult one:

    ALTER AUTHORIZATION ON DATABASE::MyDB TO sa;

    I hope it helps.

    Best regards,
    io