﻿<?xml version='1.0' encoding='UTF-8'?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/"><channel><title>SQLServerCentral / SQL Server 2008 / SQL Server Newbies  / How to eval @Variable when assigned from SELECT field? / Latest Posts</title><generator>InstantForum.NET v2.9.0</generator><description>SQLServerCentral</description><link>http://www.sqlservercentral.com/Forums/</link><webMaster>notifications@sqlservercentral.com</webMaster><lastBuildDate>Wed, 22 May 2013 14:10:09 GMT</lastBuildDate><ttl>20</ttl><item><title>RE: How to eval @Variable when assigned from SELECT field?</title><link>http://www.sqlservercentral.com/Forums/Topic1366819-1292-1.aspx</link><description>[code]3. If multiple records found in sys.columns you will NOT cause get run-time error and will be set to one of values returned by SELECT (you cannot guarantee which one) [/code]Actually you do know which one. It is the LAST value selected. With no order by on the query you don't know, but if you add an order by you know exactly which one it will return.</description><pubDate>Tue, 02 Oct 2012 11:36:46 GMT</pubDate><dc:creator>Sean Lange</dc:creator></item><item><title>RE: How to eval @Variable when assigned from SELECT field?</title><link>http://www.sqlservercentral.com/Forums/Topic1366819-1292-1.aspx</link><description>[quote][b]CELKO (10/2/2012)[/b]...Why would anyone create a local variable (like we did in 1950's assembly languages) to hold the results of an expression. We just use the expression itself in declarative languages.  ...[/quote][b]YOU[/b], may be do, but [b]WE[/b] don't! Most of modern languages do have concept of "variable" and T-SQL is one of them. Many T-SQL experts don't [b]ALWAYS[/b] use expression itself in a declarative languages such as T-SQL which allows to hold intermediate result in a variable. For example (as per given OP post) if you want to get one single record ID and then reuse it multiple times within process, the use of variable is more than reasonable!   [quote][b]CELKO (10/2/2012)[/b]...Actually, we use the ANSI/ISO Standard SET for assignment and not the old 1970's Sybase SELECT. The SELECT assignment has cardinality problems. Now look at where you did the assignment to the fake assembly language register you did with a local variable. [/quote][b]YOU[/b], may be [b]ALWAYS[/b] do, but [b]WE[/b] don't! Before SQL2008 allowed to initialise variables in time of declaration, many T-SQL experts very often used single SELECT statements to initialise multiple variables at once. Even now, it is used widely for initialising variables from relevant table/query. Actually, you kind of contradict yourself: if you would never  create a local variable (like you did in 1950's assembly languages) to hold the results of an expression why ANSI have a SET?But what is important to understand is how SELECT behaves when it's used for setting variables.Let see this:[code="sql"]DECLARE @name VARCHAR(255) = 'xxxx'SELECT @name = (SELECT name FROM sys.columns WHERE name like 'a%')SELECT @name[/code]What would be possible results of this query? It depends!1. If no records found in  sys.columns the value of @name will be reset to NULL2. If single record found in sys.columns the value of @name will set the [name] returned by select3. If multiple records found in sys.columns you will get run-time error "Subquery returned more than 1 value..."I'do, personally, really hate this behaviour, so I never using this sort of logic. Instead I am using SELECT per following:[code="sql"]DECLARE @name VARCHAR(255) = 'xxxx'SELECT @name = name FROM sys.columns WHERE name like 'a%'SELECT @name[/code]In this case: 1. If no records found in sys.columns the value of @name is not reset to NULL, so initialise value stays2. If single record found in sys.columns the value of @name will set the [name] returned by select3. If multiple records found in sys.columns you will NOT cause get run-time error and will be set to one of values returned by SELECT (you cannot guarantee which one) Here is #3 requires a special attention. if your SELECT may potentially return multiple record (as per given example), then such initialising query is most likely is not appropriate at all! However, there are some cases where it's really doesn't meter, so it can be used safely without causing run-time errors.</description><pubDate>Tue, 02 Oct 2012 09:50:02 GMT</pubDate><dc:creator>Eugene Elutin</dc:creator></item><item><title>RE: How to eval @Variable when assigned from SELECT field?</title><link>http://www.sqlservercentral.com/Forums/Topic1366819-1292-1.aspx</link><description>&amp;gt;&amp;gt;  how can I evaluate a declared variable if no valid data is returned from attempt to select a field [sic: fields are not anything like columns] into a variable? What am I missing? &amp;lt;&amp;lt;Why would anyone create a local variable (like we did in 1950's assembly languages) to hold the results of an expression. We just use the expression itself in declarative languages.  &amp;gt;&amp;gt; I've seen examples that are doing this as defined below.(yes, the temp table does have data; knowing that data I've been able to select into the variable just fine. &amp;lt;&amp;lt;Actually, we use the ANSI/ISO Standard SET for assignment and not the old 1970's Sybase SELECT. The SELECT assignment has cardinality problems. Now look at where you did the assignment to the fake assembly language register you did with a local variable. </description><pubDate>Tue, 02 Oct 2012 07:35:08 GMT</pubDate><dc:creator>CELKO</dc:creator></item><item><title>RE: How to eval @Variable when assigned from SELECT field?</title><link>http://www.sqlservercentral.com/Forums/Topic1366819-1292-1.aspx</link><description>Just a personal preference but I prefer laurie's solution.  Never liked seeing ISNULL used in that fashion.</description><pubDate>Tue, 02 Oct 2012 07:15:44 GMT</pubDate><dc:creator>brendan woulfe</dc:creator></item><item><title>RE: How to eval @Variable when assigned from SELECT field?</title><link>http://www.sqlservercentral.com/Forums/Topic1366819-1292-1.aspx</link><description>Chris, Thanks. Those are very helpful pointers on what works and does not work.  And thanks for the reference to Moden's article.  I should've included some DDL for the table referenced.. . . and the inserts for a few records.  Thinking about it, if that is all provided, then it is feasible to attempt to assist someone. Otherwise it's a real challenge.Jim</description><pubDate>Tue, 02 Oct 2012 07:10:48 GMT</pubDate><dc:creator>jmccoy-1028380</dc:creator></item><item><title>RE: How to eval @Variable when assigned from SELECT field?</title><link>http://www.sqlservercentral.com/Forums/Topic1366819-1292-1.aspx</link><description>[quote][b]ColdCoffee (10/1/2012)[/b][hr]You code should be[code="sql"]IF @MyNumberReturn = '000000' OR @MyNumberReturn IS NULLTHEN    PRINT 'NOTHING'ELSE   &amp;lt;DO SOMETHING&amp;gt; [/code][/quote]Equivalent should be:[code="sql"]IF ISNULL(@MyNumberReturn, '000000') = '000000' THEN    PRINT 'NOTHING'ELSE   &amp;lt;DO SOMETHING&amp;gt; [/code]</description><pubDate>Tue, 02 Oct 2012 04:35:36 GMT</pubDate><dc:creator>dwain.c</dc:creator></item><item><title>RE: How to eval @Variable when assigned from SELECT field?</title><link>http://www.sqlservercentral.com/Forums/Topic1366819-1292-1.aspx</link><description>You could try setting @MyNumberReturn to null instead of '000000'.Then you'd only need to check if it was null:[code="sql"]if object_id('tempdb..##tmpSlsTaxOrdsDtl') is not null	drop table ##tmpSlsTaxOrdsDtl;create table ##tmpSlsTaxOrdsDtl(OrderNo varchar(6));--insert ##tmpSlsTaxOrdsDtl values ( '123456' );Declare @MyNumberReturn as varchar(6);Declare @OrderNum as varchar(6);SET @OrderNum = '123456';SET @MyNumberReturn = NULL;SELECT  @MyNumberReturn = (SELECT OrderNo FROM ##tmpSlsTaxOrdsDtl WHERE OrderNo = @OrderNum );if (@MyNumberReturn IS NULL)	PRINT '@MyNumberReturn is null'else print @MyNumberReturn;  --if result returned to @MyNumberReturn, the data is printed.select @MyNumberReturn;[/code]Also note:  If you concatenate a string with null you get null, so this:[code="sql"]if (@MyNumberReturn IS NULL)  --get nothing	PRINT 'Invoice #: ' + @MyNumberReturn [/code]will not show anything when @MyNumberReturn is null.BTW You need to set the variable to null before running the query, because if no rows are returned the variable IS NOT UPDATED!</description><pubDate>Tue, 02 Oct 2012 02:39:54 GMT</pubDate><dc:creator>laurie-789651</dc:creator></item><item><title>RE: How to eval @Variable when assigned from SELECT field?</title><link>http://www.sqlservercentral.com/Forums/Topic1366819-1292-1.aspx</link><description>[quote][b]jmccoy-1028380 (10/1/2012)[/b][hr]Yes!  That works as desired.  Thank You! Are there other ways though, for evaluating it? [code="sql"]--something like: IF isnull(@OrderNumRtrn, 0) = 0  OR @OrderNumRtrn = '000000'      PRINT 'Do Something'ELSE      PRINT 'Do Nothing'[/code]  I did not know I couldn't SET @Variable before trying to SELECT into it, and have it be a factor. I guess I'm thinking that SELECTing into the variable would overwrite the initial string value. And, if there is nothing returned by the query,the SELECT would set @Variable to NULL.[/quote]The ISNULL function used like this offers no gains - it's a cast and a comparison instead of just a comparison.SELECTing into a variable [i]will [/i]overwrite the initial value. If a single row (and column) is returned, then the variable will be assigned the value. If more than one row is returned, then the variable will be assigned one of the values, probably the first in the result set - depending on how the valus is assigned:[code="sql"]DECLARE @name varchar(20)SELECT @name = name FROM sys.columns WHERE name = 'xptl'SELECT @name-- returns NULLSET @name = 'xxxx'SELECT @name = (SELECT name FROM sys.columns WHERE name = 'xptl')SELECT @name-- returns NULLSET @name = 'xxxx'SELECT @name = name FROM sys.columns WHERE name like 'a%'SELECT @name-- returns 'auid', last row value from 13 rowsSET @name = 'xxxx'SELECT @name = (SELECT name FROM sys.columns WHERE name like 'a%')SELECT @name-- error: Subquery returned more than 1 value. -- This is not permitted when the subquery follows =, !=, &amp;lt;, &amp;lt;= , &amp;gt;, &amp;gt;= -- or when the subquery is used as an expression.[/code]</description><pubDate>Tue, 02 Oct 2012 02:33:12 GMT</pubDate><dc:creator>ChrisM@Work</dc:creator></item><item><title>RE: How to eval @Variable when assigned from SELECT field?</title><link>http://www.sqlservercentral.com/Forums/Topic1366819-1292-1.aspx</link><description>Yes!  That works as desired.  Thank You! Are there other ways though, for evaluating it? [code="sql"]--something like: IF isnull(@OrderNumRtrn, 0) = 0  OR @OrderNumRtrn = '000000'      PRINT 'Do Something'ELSE      PRINT 'Do Nothing'[/code]  I did not know I couldn't SET @Variable before trying to SELECT into it, and have it be a factor. I guess I'm thinking that SELECTing into the variable would overwrite the initial string value. And, if there is nothing returned by the query,the SELECT would set @Variable to NULL.</description><pubDate>Mon, 01 Oct 2012 22:10:36 GMT</pubDate><dc:creator>jmccoy-1028380</dc:creator></item><item><title>RE: How to eval @Variable when assigned from SELECT field?</title><link>http://www.sqlservercentral.com/Forums/Topic1366819-1292-1.aspx</link><description>That is because you are SETting the value for your variable before the SELECT statment..[code="sql"]SET @MyNumberReturn = '000000'[/code]You code should be[code="sql"]IF @MyNumberReturn = '000000' OR @MyNumberReturn IS NULLTHEN    PRINT 'NOTHING'ELSE   &amp;lt;DO SOMETHING&amp;gt; [/code]</description><pubDate>Mon, 01 Oct 2012 16:49:48 GMT</pubDate><dc:creator>ColdCoffee</dc:creator></item><item><title>How to eval @Variable when assigned from SELECT field?</title><link>http://www.sqlservercentral.com/Forums/Topic1366819-1292-1.aspx</link><description>Hi, In code below, how can I evaluate a declared variable if  no valid data is returned from attempt to select a field into a variable?  What am I missing?  I've seen examples that are doing this as defined below.(yes, the temp table does have data; knowing that data I've been able to select into the variable just fine. . . but when nothing is returned and assigned to the variable. . .why isn't something like NULL placed in the variable? Or, the variable being varchar, wouldn't it be a len() = 0? Show me the way, please.[code="sql"]Declare @MyNumberReturn as varchar(6)Declare @OrderNum as varchar(6)SET @OrderNum = '123456'SET @MyNumberReturn = '000000'SELECT  @MyNumberReturn = (SELECT OrderNo FROM ##tmpSlsTaxOrdsDtl WHERE OrderNo = @OrderNum )--works fine if a result is returned to @MyNumRtrn--Can't eval variable if no result is returned.print len(@MyNumberReturn ) --get nothing -- how about zero as len()?if (@MyNumberReturn IS NULL)  --get nothing	PRINT 'Invoice #: ' + @MyNumberReturn else print @MyNumberReturn  --if result returned to @MyNumberReturn, the data is printed.	print '@@ERROR: ' + Convert(nvarchar(30), @@ERROR) --always = 0. [/code]</description><pubDate>Mon, 01 Oct 2012 16:40:33 GMT</pubDate><dc:creator>jmccoy-1028380</dc:creator></item></channel></rss>