开发者

SQL Query Use of CASE inside Select

Hello I have a SQL Query:

select DateDiff(d,StartDate, EndDate) DaysEmployed from ClientDayActivity

I want this to become like this:

EmployDays = CASE WHEN NOT end_date IS NULL THEN
DATEDIFF(d,start_date, end_date) ELSE   
DATEDIFF(d,start_date, CONVERT(DATETIME, '" & Cstr(strEndDate) & "', 102)) END

I pi开发者_运维知识库cked this query from old application and I have to use it according to my DB and application. I picked up this query from asp code, they had a string of query. As well as I am not getting what is this: '" & Cstr(strEndDate) & "'

Any help would be highly appreciated.


'" & Cstr(strEndDate) & "' This looks like a dynamic SQL statement from VB.

strEndDate was the name of some variable that probably contained a date that was then converted to a string using Cstr and than added to SQL statement.

If you want to do something similar in a stored proc you're probably going to want

EmployDays = CASE WHEN NOT end_date IS NULL THEN
DATEDIFF(d,start_date, end_date) ELSE   
DATEDIFF(d,start_date, @end_date) END

where @end_date is a parameter. Alternatively you can use GetDate() which would use today's date which would make some sense given the case statement logic and the column alias

Here's a sample in a select

SELECT
    CASE 
      WHEN NOT end_date IS NULL THEN
        DATEDIFF(d,start_date, end_date) 
     ELSE   
       DATEDIFF(d,start_date, @end_date) 
   END as EmployDays,
   some_other_field
FROM
       sometable
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜