Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 
        
Home       Members    Calendar    Who's On


Add to briefcase 12»»

How to eval @Variable when assigned from SELECT field? Expand / Collapse
Author
Message
Posted Monday, October 1, 2012 4:40 PM
Grasshopper

GrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopper

Group: General Forum Members
Last Login: Friday, November 16, 2012 10:40 AM
Points: 12, Visits: 39
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.

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.

Post #1366819
Posted Monday, October 1, 2012 4:49 PM
SSCrazy

SSCrazySSCrazySSCrazySSCrazySSCrazySSCrazySSCrazySSCrazy

Group: General Forum Members
Last Login: Tuesday, July 22, 2014 9:03 PM
Points: 2,262, Visits: 5,405
That is because you are SETting the value for your variable before the SELECT statment..

SET @MyNumberReturn = '000000'

You code should be

IF @MyNumberReturn = '000000' OR @MyNumberReturn IS NULL
THEN
PRINT 'NOTHING'
ELSE
<DO SOMETHING>

Post #1366825
Posted Monday, October 1, 2012 10:10 PM
Grasshopper

GrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopper

Group: General Forum Members
Last Login: Friday, November 16, 2012 10:40 AM
Points: 12, Visits: 39
Yes! That works as desired. Thank You!
Are there other ways though, for evaluating it?
--something like: 
IF isnull(@OrderNumRtrn, 0) = 0 OR @OrderNumRtrn = '000000'
PRINT 'Do Something'
ELSE
PRINT 'Do Nothing'

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.
Post #1366860
Posted Tuesday, October 2, 2012 2:33 AM


SSCertifiable

SSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiable

Group: General Forum Members
Last Login: Yesterday @ 9:56 AM
Points: 7,120, Visits: 13,491
jmccoy-1028380 (10/1/2012)
Yes! That works as desired. Thank You!
Are there other ways though, for evaluating it?
--something like: 
IF isnull(@OrderNumRtrn, 0) = 0 OR @OrderNumRtrn = '000000'
PRINT 'Do Something'
ELSE
PRINT 'Do Nothing'

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.


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 will 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:

DECLARE @name varchar(20)
SELECT @name = name FROM sys.columns WHERE name = 'xptl'
SELECT @name
-- returns NULL

SET @name = 'xxxx'
SELECT @name = (SELECT name FROM sys.columns WHERE name = 'xptl')
SELECT @name
-- returns NULL

SET @name = 'xxxx'
SELECT @name = name FROM sys.columns WHERE name like 'a%'
SELECT @name
-- returns 'auid', last row value from 13 rows

SET @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 =, !=, <, <= , >, >=
-- or when the subquery is used as an expression.



“Write the query the simplest way. If through testing it becomes clear that the performance is inadequate, consider alternative query forms.” - Gail Shaw

For fast, accurate and documented assistance in answering your questions, please read this article.
Understanding and using APPLY, (I) and (II) Paul White
Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden
Exploring Recursive CTEs by Example Dwain Camps
Post #1366900
Posted Tuesday, October 2, 2012 2:39 AM


Old Hand

Old HandOld HandOld HandOld HandOld HandOld HandOld HandOld Hand

Group: General Forum Members
Last Login: Friday, June 27, 2014 8:03 AM
Points: 320, Visits: 1,079
You could try setting @MyNumberReturn to null instead of '000000'.

Then you'd only need to check if it was null:


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;


Also note: If you concatenate a string with null you get null, so this:
if (@MyNumberReturn IS NULL)  --get nothing
PRINT 'Invoice #: ' + @MyNumberReturn

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!
Post #1366902
Posted Tuesday, October 2, 2012 4:35 AM


Hall of Fame

Hall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of Fame

Group: General Forum Members
Last Login: Yesterday @ 6:01 PM
Points: 3,609, Visits: 5,222
ColdCoffee (10/1/2012)


You code should be

IF @MyNumberReturn = '000000' OR @MyNumberReturn IS NULL
THEN
PRINT 'NOTHING'
ELSE
<DO SOMETHING>



Equivalent should be:

IF ISNULL(@MyNumberReturn, '000000') = '000000' THEN 
PRINT 'NOTHING'
ELSE
<DO SOMETHING>




My mantra: No loops! No CURSORs! No RBAR! Hoo-uh!

My thought question: Have you ever been told that your query runs too fast?

My advice:
INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.


Need to UNPIVOT? Why not CROSS APPLY VALUES instead?
Since random numbers are too important to be left to chance, let's generate some!
Learn to understand recursive CTEs by example.
Splitting strings based on patterns can be fast!
Post #1366944
Posted Tuesday, October 2, 2012 7:10 AM
Grasshopper

GrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopper

Group: General Forum Members
Last Login: Friday, November 16, 2012 10:40 AM
Points: 12, Visits: 39
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
Post #1367016
Posted Tuesday, October 2, 2012 7:15 AM
SSC Veteran

SSC VeteranSSC VeteranSSC VeteranSSC VeteranSSC VeteranSSC VeteranSSC VeteranSSC Veteran

Group: General Forum Members
Last Login: Friday, July 18, 2014 6:11 AM
Points: 208, Visits: 1,023
Just a personal preference but I prefer laurie's solution. Never liked seeing ISNULL used in that fashion.
Post #1367017
Posted Tuesday, October 2, 2012 7:35 AM


SSCommitted

SSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommitted

Group: General Forum Members
Last Login: Sunday, July 20, 2014 11:55 AM
Points: 1,945, Visits: 2,860
>> 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? <<

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.

>> 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. <<

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.


Books in Celko Series for Morgan-Kaufmann Publishing
Analytics and OLAP in SQL
Data and Databases: Concepts in Practice
Data, Measurements and Standards in SQL
SQL for Smarties
SQL Programming Style
SQL Puzzles and Answers
Thinking in Sets
Trees and Hierarchies in SQL
Post #1367033
Posted Tuesday, October 2, 2012 9:50 AM
SSCrazy

SSCrazySSCrazySSCrazySSCrazySSCrazySSCrazySSCrazySSCrazy

Group: General Forum Members
Last Login: Friday, July 4, 2014 3:55 AM
Points: 2,836, Visits: 5,062
CELKO (10/2/2012)
...
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.
...


YOU, may be do, but WE don't! Most of modern languages do have concept of "variable" and T-SQL is one of them.
Many T-SQL experts don't ALWAYS 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!

CELKO (10/2/2012)
...
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.


YOU, may be ALWAYS do, but WE 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:
DECLARE @name VARCHAR(255) = 'xxxx'
SELECT @name = (SELECT name FROM sys.columns WHERE name like 'a%')
SELECT @name

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 NULL
2. If single record found in sys.columns the value of @name will set the [name] returned by select
3. 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:

DECLARE @name VARCHAR(255) = 'xxxx'
SELECT @name = name FROM sys.columns WHERE name like 'a%'
SELECT @name

In this case:
1. If no records found in sys.columns the value of @name is not reset to NULL, so initialise value stays
2. If single record found in sys.columns the value of @name will set the [name] returned by select
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)

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.


_____________________________________________
"The only true wisdom is in knowing you know nothing"
"O skol'ko nam otkrytiy chudnyh prevnosit microsofta duh!"
(So many miracle inventions provided by MS to us...)

How to post your question to get the best and quick help
Post #1367134
« Prev Topic | Next Topic »

Add to briefcase 12»»

Permissions Expand / Collapse