Click here to Skip to main content
15,884,237 members
Please Sign up or sign in to vote.
2.67/5 (2 votes)
See more:
SQL
CREATE FUNCTION [dbo].[getEquipmentName]
 (@EquipmentId varchar(500))
RETURNS varchar(500)
AS
begin
declare @EquipmentName varchar(500)

select @EquipmentName = EquipmentName
FROM   PMS_TBL_EQUIPMENT_MASTER where convert(varchar(60),UniqueId)=@EquipmentId

if @EquipmentName is null

select @EquipmentName = SubEquipmentName
FROM   PMS_TBL_SUB_EQUIPMENT_MASTER where convert(varchar(60),UniqueId)=@EquipmentId
if @EquipmentName is null
  select @EquipmentName = SubFunctionalBlockName
FROM   PMS_TBL_SUB_FUNCTIONAL_BLOCK_MASTER where convert(varchar(60),UniqueId)=@EquipmentId
if @EquipmentName is null
 select @EquipmentName=''''

return  @EquipmentName
end


can any one suggest me to reduce the above code into a single select statement?
Posted
Comments
Sreekanth Mothukuru 27-Oct-15 10:01am    
I think we can make use of "Case when then" or "IIF" statement in SQL Server to get it done in a single line..

I'm afraid you can't use single SELECT statement, because you're searching for single value in many tables. So, the best way is to merge data using UNION (ALL)[^] statement.

SQL
SELECT @EquipmentName = COALESCE(EquipmentName, '')
FROM (
    SELECT EquipmentName
    FROM PMS_TBL_EQUIPMENT_MASTER
    UNION ALL
    SELECT SubEquipmentName
    FROM PMS_TBL_SUB_EQUIPMENT_MASTER
    UNION ALL
    SELECT SubFunctionalBlockName
    FROM PMS_TBL_SUB_FUNCTIONAL_BLOCK_MASTER
) AS T
WHERE CONVERT(VARCHAR(60),UniqueId)=@EquipmentId
 
Share this answer
 
Your set of queries can be written in either Case when then or "IIF" or using "COALESCE".

The best approach would be using "COALESCE" like this:

SQL
SELECT COALESCE(<first select statement>, <second select statement>, <third select statement>);


For more information follow this link:
https://msdn.microsoft.com/en-IN/library/ms190349.aspx[^]
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900