Thursday, 19 January 2012

case in SQL Server



 CASE in SQL Server


 a small examle to explain what we do with case in SQL




below is a condition where i need to show cratefrom & crate_to in such a way
so that they will look like this
1-15  (means cratefrom - crate_to)


but i also need to assure my self that if any where the cratefrom & crate_to are same then just show sigle one for eg cratefrom


below is code how you can do this!



SELECT [pck_id] ,[pi_no] ,[cal_id],[rue_id] ,[rue_no] ,[p_date] ,[product_type]
       ,[product_name],[size] ,[qty],[crateFrom],[crate_to],
    case when [crateFrom]=[crate_to] then [crate_to]
    else 
    ltrim(rtrim([crateFrom]))+'-'+ltrim(rtrim([crate_to])) 
    end as crate  
  FROM [dbo].[tbl_packinglist] GO


if you didnt understand the ltrim & rtrim,its nothing but just triming the values

like if the execute query gives you this
1    -12

then
ltrim & rtrim(lefttrim & rightrtrim(by side))
will give you this 

1-12

1 comment:

  1. Basic work of TRIM() is to remove trailing and heading spaces.In sqlserver there this function is divided in two parts LTRIM(){Removes Heading spaces} and RTRIM(){Removes Trailing Spaces}

    ReplyDelete

Print Only Grid View in ASP.net

ASP.net How to Print Only GridView < div id ="gridviewDiv" >   < asp:GridView ID ="gridViewToPri...