TSQL variable

  • Comments posted to this topic are about the item TSQL variable

    Tariq
    master your setup, master yourself.
    http://mssqlsolutions.blogspot.com

  • Since isnull(@var,1)=1 then the following code should be equivalent to the original:

    Declare @var int

    Select @var = 1+ Value1

    From (Select 1 Value1 Union All Select 1 Union All Select 2) as a

    Select @var

    But it isn't - the answer this time is 3.

    Why does the isnull function have the effect of causing the Value1 column to be summed into @var?

  • isnull function select the 1 whn @var is null or first time , second time @var=2 , n third time it will 3 n next so ans is 5

    but in @var=1+value1

    the @var1 is always 1

    so ans is 3

  • Right 🙂

    Thanks.

  • shnizzle (8/29/2008)


    Since isnull(@var,1)=1 then the following code should be equivalent to the original:

    Declare @var int

    Select @var = 1+ Value1

    From (Select 1 Value1 Union All Select 1 Union All Select 2) as a

    Select @var

    But it isn't - the answer this time is 3.

    Why does the isnull function have the effect of causing the Value1 column to be summed into @var?

    Hi Shnizzle,

    Very good point. The output from your version can be either 2 or 3, as there is no documentation on which row should be processed "last" (and hence, which of the possible results should "stick").

    And for the original query, those two answers (2 and 3) are actuallly just as correct as the more common answer (5). Because the behaviour of SELECT @var = @var + something is not documented, you can just as well defend that this should be evaluated for each row with the original value of @var, instead of the current observed behaviour that takes the new value of @var in account for each following row. And since it's undocumented, the alternative behaviour might just become the current behaviour on the next version, service pack, or maybe even after a bugfix or when the query processor decides on a different execution plan.


    Hugo Kornelis, SQL Server/Data Platform MVP (2006-2016)
    Visit my SQL Server blog: https://sqlserverfast.com/blog/
    SQL Server Execution Plan Reference: https://sqlserverfast.com/epr/

  • Hugo, is it not documented or documented as not defined? This code reminded me of a function I use that operates on the same principle in order to concatenate column data over multiple rows for a certain UserID:

    SET @ComplaintList = ''

    SELECT @ComplaintList = @ComplaintList+ UserComplaint+ char(13)

    FROM ComplaintsTable

    WHERE UserID=@UserID

    ..

    Return @ComplaintList

    And it does iterate over all the relevant rows and gives the expected result.

    Where can I find more about this?

  • shnizzle (8/29/2008)


    Hugo, is it not documented or documented as not defined? This code reminded me of a function I use that operates on the same principle in order to concatenate column data over multiple rows for a certain UserID:

    SET @ComplaintList = ''

    SELECT @ComplaintList = @ComplaintList+ UserComplaint+ char(13)

    FROM ComplaintsTable

    WHERE UserID=@UserID

    ..

    Return @ComplaintList

    And it does iterate over all the relevant rows and gives the expected result.

    Where can I find more about this?

    Hi Shnizzle,

    As far as I know, the syntax of queries such as yours is not covered anywhere in Books Online. This by itself is sufficient for me to not use this in production code.

    In the knowledge base, there is an explicit article that warns about unexpected results if such queries depending on the exact location of an ORDER BY clause: http://support.microsoft.com/default.aspx/kb/287515. If you run the repro code, you'll see that in some cases the results are incomplete. Though this article is specifically about ORDER BY, I would never take this to imply that these queries are reliable if no ORDER BY is used.


    Hugo Kornelis, SQL Server/Data Platform MVP (2006-2016)
    Visit my SQL Server blog: https://sqlserverfast.com/blog/
    SQL Server Execution Plan Reference: https://sqlserverfast.com/epr/

  • Hugo, I read the KB article and even when taking it into account, I think that my code is correct - it looks exactly as the statement described in the 'Workaround' section, sans the 'ORDER BY'.

  • Hugo, about your code:

    SET @ComplaintList = ''

    SELECT @ComplaintList = @ComplaintList+ UserComplaint+ char(13)

    FROM ComplaintsTable

    WHERE UserID=@UserID

    ..

    Return @ComplaintList

    I thought that might be something I could use for various things, but I cannot get the code to work, even with the .. commented out. Is there something missing from the code (I of course substituted my name for yours)

    Nancy

  • shnizzle (8/29/2008)


    Hugo, I read the KB article and even when taking it into account, I think that my code is correct - it looks exactly as the statement described in the 'Workaround' section, sans the 'ORDER BY'.

    Hi Shnizzle,

    Personally, I don't consider this article as implying that it SHOULD work, and that it ALWAYS WILL work. And I value very much the fact that the syntax "SELECT @var = @var + SomeColumn FROM ..." is not mentioned in Books Online at all very telling.

    If you still want to implement this and put it in production, feel free to do so ... but never forget that it IS undocumented, so you'll have to retest after every service pack, every patch, and every hardware update and still be prepared to be surprised. The fact that many users do use this and do rely on this does not guarantee that Microsoft won't change it - just remember what happened to GROUP BY without ORDERY BY when upgrading from SQL 6.5 to SQL 7.0, or to views with TOP 100 PERCENT and ORDER BY when upgrading to SQL 2000 to SQL 2005. For my production code, I'll stick to officially documented code. 🙂


    Hugo Kornelis, SQL Server/Data Platform MVP (2006-2016)
    Visit my SQL Server blog: https://sqlserverfast.com/blog/
    SQL Server Execution Plan Reference: https://sqlserverfast.com/epr/

  • Nancy, it was just a snippet. here's the whole function:

    CREATE FUNCTION [dbo].[fnConcatUserComplaints] (@UserId int)

    RETURNS varchar(8000)

    AS BEGIN

    DECLARE @strReturn VARCHAR(max)

    SET @strReturn = ''

    SELECT @strReturn = @strReturn+ ComplaintDetail+ char(13)

    FROM ComplaintsTable

    WHERE UserId=@UserId

    RETURN @strReturn

    END

  • nancy.lytle (8/29/2008)


    Hugo, about your code:

    SET @ComplaintList = ''

    SELECT @ComplaintList = @ComplaintList+ UserComplaint+ char(13)

    FROM ComplaintsTable

    WHERE UserID=@UserID

    ..

    Return @ComplaintList

    I thought that might be something I could use for various things, but I cannot get the code to work, even with the .. commented out. Is there something missing from the code (I of course substituted my name for yours)

    Nancy

    Hi Nancy,

    This code was not posted by me, but by Shnizzle.

    Code such as this is not documented and not guaranteed to do what you might expect (and frankly, I don't even know exactly WHAT you expect, as there's more than one result that can be argued to be correct). However, many people seem to report consistent results and choose to rely on this undocumented construction.

    Maybe you can post your actual code, along with CREATE TABLE statements for your tables, INSERT statemtents for your test data, and the required results. There might be a better way to achieve what you need.


    Hugo Kornelis, SQL Server/Data Platform MVP (2006-2016)
    Visit my SQL Server blog: https://sqlserverfast.com/blog/
    SQL Server Execution Plan Reference: https://sqlserverfast.com/epr/

  • Interesting technique! I can think of places where I can use this. Thanks!

  • To add weight to Hugo's argument, here's a bit from BOL that seems relevant:

    Caution:

    If there are multiple assignment clauses in a single SELECT statement, SQL Server does not guarantee the order of evaluation of the expressions. Note that effects are only visible if there are references among the assignments.

    If a SELECT statement returns more than one row and the variable references a nonscalar expression, the variable is set to the value returned for the expression in the last row of the result set. For example, in this batch @EmpIDVariable is set to the EmployeeID value of the last row returned, which is 1:

    USE Northwind

    GO

    DECLARE @EmpIDVariable int

    SELECT @EmpIDVariable = EmployeeID

    FROM Employees

    ORDER BY EmployeeID DESC

    SELECT @EmpIDVariable

    GO

    Now, of course the QOD result doesn't depend on the order in which the rows are evaluated, but it does depend on all the rows being evaluated. In the BOL example, the lowest EmployeeID is placed in the variable, apparently because it's the last one evaluated by a query that examines each row in table Employees in descending order by Employee.

    But what if someone at Microsoft were to improve the performance of this query by tweaking the optimizer to take advantage of an index on EmployeeID and simply return the equivalent of min(EmployeeID)? The query behavior would still meet the description in BOL, only run a bit faster.

    Then, even without an "order by" clause, it may be reasonable for the query to still use the value of the last row, even if that is by rule unpredictable. That brings us back to Hugo's point, which is that it can be dangerous to depend upon undocumented behavior of a db engine. By the rules, he's right that the answer could well be 2 or 3, depending on the implementation of the documented expected results for a query in this form.

  • Sorry about that, actually I was just thinking it would be another way to gets lists, but I can do that with regular queries. I just hadn't used that type of technique and thought it looked interesting. But since I can't get it to work in SS2005, and some of you are saying it can't be trusted, I will abandoned my 'playing' with it.

    Thanks,

    Nancy

Viewing 15 posts - 1 through 15 (of 20 total)

You must be logged in to reply to this topic. Login to reply