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

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. e.g
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 i.e. 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)

Related

SQL - Conversion failed when converting date and/or time from character string

I have 3 tables in the database that I'm working on. Out of 3, two of the tables have columns that include dates. When I checked the information schema of the columns I found that dates have the wrong data type. If you see the picture below, the highlighted columns should be stored as DATE data type.
So, I used the following query to change their data type from varchar to DATE:
ALTER TABLE [dbo].[Customer]
ALTER COLUMN DOB DATE;
ALTER TABLE [dbo].[Transactions]
ALTER COLUMN tran_date DATE;
The error that I get is:
Conversion failed when converting date and/or time from character string.
Please let me know how I can fix this error. Thanks!
What you can do is update the value using try_convert() first and then alter the column name. Note: This will set any invalid values to NULL.
update customer
set dob = try_convert(date, dob);
alter table customer alter column dbo date;
If you want to see the bad values, then before you change the table, run:
select c.*
from customer c
where try_convert(date, dob) is null and dob is not null;
You may have other ideas on how to fix the values.
You can't change from varchar to date or time or datetime by altering the column. Why? Because SQL Server does not know if the field contains '1/1/2020' or 'My dog is cute'. You will have to rebuild the table with the proper data types and then CAST() or CONVERT() the values to a true date time.
Underneath the hood, this makes more sense. A char/varchar uses one byte per character. nchar/nvarchar uses 2 bytes per character. A datetime is a number, not a character. This means you need a routine that changes this into the correct number. If you want to get deeper, the number is the number of ticks (nanoseconds) since midnight on January 1, 0001 in the Gregorian Calendar. More info.

Insert Date and String on table

I have a table with the following properties:
U. TRADE_ID VARCHAR2
TRADE_DATE DATE
PRICE NUMBER(10.2)
Once I get the data from a file, the colums are as follow:
PSD231,03051982,50.1
My question is, are those the correct datatypes for the table? I'm getting the input from the file for the first sql column as a String. But I can't display it. I think I'm missing something in the sql part. How can I create a new sql row filled with data so I can test it? This is what I tried and works:
insert into myTable(TRADE_ID, TRADE_DATE, PRICE)
values('PSD231', date '2011-01-01', 10.4);
but I'm trying create a query with the date in the format:
01-01-2011, not like the above
"What if I wanted to insert the values like this: 10062019 in the format ddmmyyyy instead of how I have it in the query: 2011-01-01 "
Just put single quotes around the date, '10062019', and make sure it is in the correct date format for your region (ddmmyyyy in your case).
insert into myTable (TRADE_ID, TRADE_DATE, PRICE)
values ('PSD231', '20110101', 10.4);
To change date formats, use the CONVERT function e.g
SELECT CONVERT(varchar, getdate(), 1)
There is a nice list for the convert function here
Since you have defined the first field as a varchar type, it should be more like,
insert into myTable(TRADE_ID, TRADE_DATE, PRICE)
values('PSD231','2011-01-01', '10');
Values should be enclosed into single quotes when they are being inserted.

Adding a date column and a nvarchar column together

I have 3 columns in my Test table that look like this
DATE TIME Combined
2015-08-17 16:07:49
2015-08-18 08:13:23
2015-08-18 08:13:24
2015-08-18 08:14:36
What I want to do is combine the Date and Time column to populate the Combined Column
The DATE column is actually a date Data Type.
The Time column is actually a nvarchar(MAX) Data Type.
I'm not exactly sure what to use for the Combined column.
Is it possible to add the two together as they are or do I have to convert the time and if so how do I do this conversion?
I have used:
alter table [dbo].[Test] alter column [TIME] time(0)
and have received this error message:
Conversion failed when converting date and/or time from character string.
Does anyone have have any insight for me on this and if I even need to convert it?
The data type for the combined column should be datetime2 (or datetime) as that is what it will hold.
You can't add a varchar value to a date type value, but to populate it you can cast the [date] column to a datetime and add the varchar string with the time part to it like this:
update dbo.test set combined = cast([date] as datetime) + [time] from dbo.test
This does however rely on the values in the [time] column being valid, and the error message you get indicates that some value(s) isn't, so you need to identify and correct those values first.
Example SQL Fiddle
for Display try,
select [Date]+' ' + Time as CombinedColumn from Test

converting varchar to date format in sql server

I have a table with two date column. However the columns are in varchar. I need to covert them as date format.
The sample data is like this:
Account Number | Registration Date | System Status Change Date
01740567715 | 10-JUL-13 | 30-JUL-13 12.53.32.000000000 PM
I want both of these columns like this: 10-Jul-2013.
For Registration Date, I am using this code:
Update [dbo].[SysDataV2]
Set ["REGISTRATION_DATE"]= convert(datetime, (["REGISTRATION_DATE"]), 106)
But it is shwoing the result as varchar and also showing erroneous format.
For System Status Change Date I am using following code:
update [dbo].[SysData]
Set ["KYC_STATUS_CHANGED_DATE"]= REPLACE(CONVERT(datetime,convert(datetime,left(["KYC_STATUS_CHANGED_DATE"],9),103),106),' ' ,'-')
Both are changing to date format of some type (not my expected format) but in table structure they are still shown as varchar.
What am I doing wrong here?
The table's data type is still varchar. An update merely changes the string, it doesn't change the data type. What you should do is (assuming all of the dates are valid and this format is 100% consistent):
UPDATE dbo.SysData SET REGISTRATION_DATE =
CONVERT(CHAR(10), CONVERT(DATE, REGISTRATION_DATE, 106), 120);
UPDATE dbo.SysData SET KYC_STATUS_CHANGED_DATE =
CONVERT(CHAR(10), CONVERT(DATETIME, LEFT(KYC_STATUS_CHANGED_DATE, 9), 106), 120)
+ REPLACE(SUBSTRING(KYC_STATUS_CHANGED_DATE, 10, 9), '.',':')
+ RIGHT(KYC_STATUS_CHANGED_DATE, 2);
ALTER TABLE dbo.SysData ALTER COLUMN REGISTRATION_DATE DATE;
ALTER TABLE dbo.SysData ALTER COLUMN KYC_STATUS_CHANGED_DATE DATETIME;
And then stop inserting regional and potentially problematic strings. String literals representing dates / datetimes should be:
-- date only
YYYYMMDD
-- with time:
YYYY-MM-DDThh:mm:ss.nnn
But best is to simply make sure they are date or datetime values before you ever hand them off to SQL Server. Your application should be able to do this without ever converting to some arbitrary string format. Never, ever, ever store date or datetime values as strings in SQL Server. You gain nothing and you lose quite a lot.
You need to change the data type of the column from a varchar to store it as a Date. Then when you select it you can format it any way that you like. One way to do this would be to create a new column of the correct datatype and convert the data, then remove the old column. Make sure the the old column doesn't have and foreign key relationships or you will also need to transfer those over as well.
ALTER TABLE [dbo].[SysData] ADD ConvertedDate DateTime
UPDATE [dbo].[SysData] SET ConvertedDate = CAST(VarCharDate as DateTime)
ALTER TABLE [dbo].[SysData] DROP COLUMN VarCharDate

How to Insert table column values: month & day from column datetype

I'm using Oracle 11g Schema
I want to select the month and day from a date concatenate it and put it into a column.
The syntax I have here makes sense but its throwing an error of..
INSERT INTO OB_SELECT_LST12_SPG WED
VALUES (((TO_CHAR(TO_DATE('RET_DATE', MM))||( TO_CHAR(TO_DATE('RET_DATE', DD)));
"SQL Error: ORA-00907: missing right parenthesis"
Any help is greatly appreciated.
Thanks.
Some points first...
Your table name has a space in in
Your not enough columns error is caused by you having more than one column in the table
You really shouldn't be doing this at all
If ret_date is a column don't encapsulate it in quotation marks (') as you won't be able to convert the string 'ret_date' into a date.
However, assuming ret_date is a string that looks like 13-06-2012
insert into ob_select_lst12_spg_wed (my_column)
values(to_char(to_date(:ret_date,'dd-mm-yyyy'),'mmdd'));
If ret_date is a date data-type then you can remove the inner conversion.
insert into ob_select_lst12_spg_wed (my_column)
values(to_char(:ret_date,'mmdd'));
to_char and to_date both make use of datetime format models, which have a number of options.
Please don't do this though. Always store dates as dates
From your comments ret_date is a date and the column wed is a character. You're getting the error bind variable not declared because you haven't specified the variable. I'm going to assume that ret_date is in another table as it's a date, in which case lose the values key-word and insert directly from that table:
insert into ob_select_lst12_spg (wed)
select to_char(ret_date,'mmdd')
from the_other_table
This shouldn't be required though, you can always convert a date into whatever you want on exit from the database. If you don't store it as a date in the database then it's easy for errors and incorrect values to creep in. I personally would change the column wed to a date, in which case your query becomes the very simple:
insert into ob_select_list12_spg (wed)
select ret_date
from the_other_table
You can then use the correct datetime format model for your needs when selecting from the database.
Sample query to get date, month from date column:
Select ((To_Char(to_date('01-FEB-73','dd-mon-yy'), 'MM'))
||( To_Char(to_date('01-JAN-73','dd-mon-yy'), 'dd')))
from dual;
if RET_DATE is date datatype then use
insert into table_name (columname)
Select ((To_Char(RET_DATE, 'MM'))
||( To_Char(RET_DATE, 'dd')))
from dual;
You are missing extra parentheses. Number of opened ( was 8 and closed ) was 5
INSERT INTO OB_SELECT_LST12_SPG(WED)
VALUES ((TO_CHAR(TO_DATE(RET_DATE, MM)))||( TO_CHAR(TO_DATE(RET_DATE, DD))));
Update
Make sure other columns are not required (i.e. Allow NULLs)