Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
SQL brain freeze
Message
 
 
To
23/02/2017 11:11:52
General information
Forum:
Microsoft SQL Server
Category:
SQL syntax
Miscellaneous
Thread ID:
01648427
Message ID:
01648428
Views:
61
This message has been marked as the solution to the initial question of the thread.
>9,999 times out of 10,000 there will be a row.
>How can I avoid the second query here?
>
>
>
>CREATE FUNCTION dbo.GetStoreNameAndAddress           -- function name
>(@storecode CHAR(11))                     -- input parameter name and data type
>RETURNS CHAR(50)                          -- return parameter data type
>AS
>BEGIN                                -- begin body definition
>DECLARE @StoreNameAndAddress CHAR(50)
>IF EXISTS (select * FROM store where LEFT(storecode,11) = @storecode)
>   SELECT @StoreNameAndAddress = ( select RTRIM(store_name) + ' ' + RTRIM(f_address) from store where LEFT(storecode,11) = @storecode)
>ELSE
>     SELECT @StoreNameAndAddress = 'Unknown Store'
>RETURN @StoreNameAndAddress
>END
>GO
>
Don't use scalar functions.

You may use
select @StoreNameAndAddress = rtrim(store_name) + ' ' + ... from store where storeCode like @storeCode + '%'

if @@ROWCOUNT = 0
   select @StoreNameAndAddress = 'Unknown Store'
BTW, it should return varchar and not char unless you want to save spaces.

--------------------------------------
Since scalar functions don't play well in SQL Server, I suggest to incorporate it into your main query using OUTER APPLY, then you would be able to use ISNULL function to get the 'Unknown Store'
If it's not broken, fix it until it is.


My Blog
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform