SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 SQL Server 2012 Forums
 Transact-SQL (2012)
 Return 0 if record does not exists
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

Ciupaz
Posting Yak Master

Italy
232 Posts

Posted - 01/30/2013 :  10:02:29  Show Profile  Reply with Quote
Hello all,
having this query:

DECLARE @k DECIMAL(18,10)
SELECT @k = ISNULL(value,0) FROM app.T_Fatt
WHERE UP_ID = 829
PRINT @k

because the record with UP_ID how can I force to return 0 instead of nothing?

Luigi

James K
Flowing Fount of Yak Knowledge

3704 Posts

Posted - 01/30/2013 :  10:04:27  Show Profile  Reply with Quote
Initialize it to zero.
DECLARE @k DECIMAL(18,10) = 0;

Go to Top of Page

Lamprey
Flowing Fount of Yak Knowledge

4614 Posts

Posted - 01/30/2013 :  12:12:31  Show Profile  Reply with Quote
James, solution will just fine. However, we use a slightly different pattern to help avoid situations where a query could return more than one row (thus assigning a random value to the variable). With this pattern SQL will error if more than one vaue is returned and it is mroe ovbious what you are trying to achomplish (i.e.: you want a zero result and not a null):
DECLARE @Foo TABLE (ID INT, Val VARCHAR(20))

DECLARE @Bar INT


SET @Bar = COALESCE
	(
		(
			SELECT ID
			FROM @Foo
			WHERE Val = 'Test'
		)
		, 0
	)

SELECT @Bar
Go to Top of Page

Ciupaz
Posting Yak Master

Italy
232 Posts

Posted - 01/30/2013 :  14:14:31  Show Profile  Reply with Quote
They're both useful solutions.
Thank you all.

Luigi
Go to Top of Page

James K
Flowing Fount of Yak Knowledge

3704 Posts

Posted - 01/30/2013 :  18:46:15  Show Profile  Reply with Quote
Thanks Lamprey! Ciupaz, if there is the possibility that there would be more than one row for a given UP_ID, use Lamprey's suggestion - especially so if for some of those rows the value column happens to have NULLs.
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.06 seconds. Powered By: Snitz Forums 2000