question

innap9999 avatar image
innap9999 asked

Set up datetime column to 'n/a'

I am creating Stored Procedure which will count last Sunday date only when it executed on Sunday, in all other days it should return "n/a". select @CurrentSun = (CASE WHEN datepart(dw,@Editiondate) = 1 Then dateadd(dd, (-1)*(datepart(dw, @Editiondate)-1) , @Editiondate) WHEN datepart(dw,@Editiondate) <> 1 then ???? Thanks
date
1 comment
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Grant Fritchey avatar image Grant Fritchey ♦♦ commented ·
This site runs off of votes. Please mark all helpful answers by clicking on the thumbs up next to those answers. If any one answer lead to a solution, please indicate that by clicking on the check mark next to that answer.
0 Likes 0 ·
KenJ avatar image
KenJ answered
'n/a' isn't a date, so can't be assigned to the same variable that would normally hold a date or datetime value. You'll need to use a string variable and return the date of the previous Sunday as a string by using convert(). That way you can return 'n/a' on the other days without an error - [ http://msdn.microsoft.com/en-us/library/ms187928.aspx][1] ... THEN convert(varchar(20), dateadd(dd, (-1)*(datepart... WHEN datepart(dw,@Editiondate) <> 1 then 'n/a' [1]: http://msdn.microsoft.com/en-us/library/ms187928.aspx
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Venkataraman avatar image
Venkataraman answered
You can return NULL instead of N/A. As mentioned by KenJ, 'n/a' is character value and cannot be assigned to datetime variable. select @CurrentSun = (CASE WHEN datepart(dw,@Editiondate) = 1 Then dateadd(dd, (-1)*(datepart(dw, @Editiondate)-1) , @Editiondate) WHEN datepart(dw,@Editiondate) 1 then NULL
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Wilfred van Dijk avatar image
Wilfred van Dijk answered
When datepart is week (wk, ww) or weekday (dw), the return value depends on the value that is set by using SET DATEFIRST. I recomment to use this setting to validate the assumption day 1 = sunday (and you'll know: "assumption is the mother of all ...")
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

innap9999 avatar image
innap9999 answered
Thank you, I signed that part to Null and then used case: case when @CurrentSun is null then 'n/a' else cast(datepart(mm,@CurrentSun)as char(2)) + '-' + cast(datepart(dd,@CurrentSun)as char(2)) + ' ' + 'Su BD' end as SuBD ,
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.