SQL Server - explanation

Asked By ali shaik on 03-Mar-12 07:55 AM
will you please explain me the code which is given below,,,,,,,i have  a doubt about y should we use varchar type???


               CONVERT(date, '01-' + Convert(varchar(2),Month) + '-' + Convert(varchar(4),Year )) between CONVERT(date, '01-' + Convert(varchar(2),11) + '-' + Convert(varchar(4),2011)) and CONVERT(date, '01-' + Convert(varchar(2),12) + '-' + Convert(varchar(4),2011))
Chintan Vaghela replied to ali shaik on 03-Mar-12 08:43 AM
hello

using  Varchar , if you want to format date in different then need to use Varchar

Format like, mm/dd/yyyy. yyyy-mm-dd etc.

D Company replied to ali shaik on 03-Mar-12 09:30 AM
Hello.

As we know that we can't convert Datetime in specific format, so the only  way to translate a DateTime into a specific format is to convert it to a varchar or other string data type.  This means that it is no longer a DateTime.  It is a varchar

so if u required to insert or compare in a specific format than it would be good to go with varchar

hope its clear
D
Web Star replied to ali shaik on 03-Mar-12 12:06 PM
Actually this query is completely wrong written. See below with break it

CONVERT

(date, '01-' +

Convert(varchar(2),Month) + '-' + Convert(varchar(4),Year )

)

between

CONVERT(date, '01-' + Convert(varchar(2),11) + '-' + Convert(varchar(4),2011))

and

CONVERT(date, '01-' + Convert(varchar(2),12) + '-' + Convert(varchar(4),2011))

 In above query every thing is wrong, actually date comparision using between two date
if column need to check between range than you use

colname between fromdate and todate
When you want to convert it when using query than
CONVERT(data_type(length),expression,style)


So you can convert datetype by using convert either from date to varchar or varchar to date both are possible but this is matter your expression should be valid value to convert it to date type or varchar