简体   繁体   中英

Concatenate Constant value in string in where or Order by clause in sql server?

I have a column named BillsOfMonth (nvarchar) in which i have only Month and year values in format Jan-2014, Feb-2014 , Mar-2014
I want to convert it to Date Format and order by Date. i have tried

select rid
     , name
     , billsofmonth 
  from reports 
 order by 
       CONVERT (datetime, "1-" & billsofmonth)

Since "1-" & billsOfMonth which is Jan-2014 will become '1-Jan-2014'.
But convert will work only in Columns.
How can i concatenate Constant String to column BillsOfMonth and convert it to date? I can not make Function and T-Statement. I Can Only Use Query.

You should use single quotes instead of double quotes, and also use + not & to concatenate strings:

ORDER BY CONVERT(DATETIME, N'1-' + billsofmonth);

For what it's worth, there is no need to store this as NVARCHAR, VARCHAR would do just fine as there are no non-ascii characters in the format you are using. This article on choosing the wrong data type is a useful read. Although better still would be to store it as a date, making it the first of month, then put in a check constraint to ensure only the first day of the month is used. eg

CREATE TABLE Reports
(
        BillsOfMonth DATE NOT NULL,
    CONSTRAINT CHK_Reports_BillsOfMonth CHECK (DATEPART(DAY, BillsOfMonth) = 1)
);

This provides much more flexibility with comparison, and ensuring data integrity ie I with your column I could enter 'xxxxxxx', which would go into the column fine, but when you came to run the convert to datetime an error would be thrown. The check constraint would stop any invalid entries, so if I ran:

INSERT Reports (BillsOfMonth) VALUES ('20140502');

I would get the error:

The INSERT statement conflicted with the CHECK constraint "CHK_Reports_BillsOfMonth". The conflict occurred in database "TestDB", table "dbo.Reports", column 'BillsOfMonth'.

Then if you will often need your date in the format MMM-yyyy you could add a computed column:

CREATE TABLE Reports
(
        BillsOfMonth DATE NOT NULL,
        BillsOfMonthText AS LEFT(DATENAME(MONTH, BillsOfMonth), 3) + '-' + DATENAME(YEAR, BillsOfMonth),
    CONSTRAINT CHK_Reports_BillsOfMonth CHECK (DATEPART(DAY, BillsOfMonth) = 1)
);

Example on SQL Fiddle

What if you try like this

select rid,
name,
convert (datetime, (N'1-'+billsofmonth)) as NewBills
from reports 
order by NewBills

I found what i am doing wrong. In Sql Server we use single inverted comma (') for constant expression not double inverted comma ("). So, It will be

SELECT [rid] ,[name], [billsofmonth] FROM [reports] order by CAST ( ('1-' + billsofmonth) as datetime)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM