Conversion error in SQL Server? - sql

In my SQL query:
insert into Tbl_EmpMovement_T values (
'004101',
'2011-8-26',
CONVERT(datetime,convert(varchar(10),'2011-8-26',120)+' ' +
CONVERT(varchar(2),SUBSTRING('8:16',1,2))+':'+
convert(varchar(2),SUBSTRING('8:16',4,2))+':00.000',120),
CONVERT(datetime,convert(varchar(10),'2011-8-26',120)+' ' +
CONVERT(varchar(2),SUBSTRING('6:02',1,2))+':'+
convert(varchar(2),SUBSTRING('6:02',4,2))+':00.000',120)
)
I am getting this error
Conversion failed when converting date and/or time from character
string.

I would rather try this:
insert into Tbl_EmpMovement_T values (
'004101',
'2011-8-26',
CAST ('2011-8-26' + ' ' +
( SUBSTRING('16:02',0, PATINDEX('%:%', '16:02')+1)) +
( SUBSTRING('16:02',PATINDEX('%:%', '16:02')+1, 2)) AS datetime),
CAST ('2011-8-26' + ' ' +
( SUBSTRING('16:02',0, PATINDEX('%:%', '16:02')+1)) +
( SUBSTRING('16:02',PATINDEX('%:%', '16:02')+1, 2)) AS datetime)
)
This way, you wont have a problem when the time part moves between single and double digit hours.

Related

SQL Server formatting negative values from selected data

I am new to stackoverflow but I do search it often.
I am creating a report from data in which I have to format negative numbers like,
-00000010 (9 characters max)
I am getting this,
000000-10
This is what I am attempting now but I'm having issues. Any help would be greatly appreciated.
SELECT 'H'
+ DG.BLOCK
+ LEFT(DG.ZIP,5)
+ RIGHT('000000000'
+ CAST(CAST(SUM(DG.WP)AS INT) AS VARCHAR(9)),9)
+ RIGHT('000000000' + CAST(CAST(SUM(DG.WE)AS INT) AS VARCHAR(9)),9)
+ RIGHT('000000000' + CAST(CAST(SUM(DG.EP)AS INT) AS VARCHAR(9)),9)
+ RIGHT('000000000' + CAST(CAST(SUM(DG.EE)AS INT) AS VARCHAR(9)),9)
+ RIGHT('000000000' + CAST(CAST(COUNT(DGG.CLAIMCONTROL)AS INT) AS VARCHAR(9)),9)
+ RIGHT('000000000' + CAST(CAST(SUM(DGG.INC) AS INT) AS VARCHAR(9)),9)
+ RIGHT('000000000' + CAST(CAST(SUM(DGG.PAID)AS INT) AS VARCHAR(9)),9)
+ RIGHT('000000000' + CAST(CAST(SUM(DGG.ALAE) AS INT) AS VARCHAR(9)),9)
AS [H Record]
FROM TABLE
If 2012+, you have the option of Format().
Example
Select replace(format(-1,' 000000000'),'- ','-')
Returns
-000000001 If number was negative
000000001 If number was positive
Just a word of caution. Format() has some great functionality, but is not known to be a high performer.
The following code demonstrates formatting the data as either 9 digits plus an optional sign or as a fixed 9 characters including the sign.
-- Sample data.
declare #Samples as Table ( Sample Int );
insert into #Samples ( Sample ) values ( 0 ), ( 1 ), ( -10 ), ( 100 ), ( -1000 );
-- Format the data.
select Sample,
case when Sign( Sample ) = -1 then '-' else '' end +
Right( Replicate( '0', 8 ) + Cast( Abs( Sample ) as VarChar(9) ), 9 ) as FormattedSample9PlusSign,
case when Sign( Sample ) = -1 then
'-' + Right( Replicate( '0', 7 ) + Cast( -Sample as VarChar(8) ), 8 ) else
Right( Replicate( '0', 8 ) + Cast( Sample as VarChar(9) ), 9 ) end as FormattedSample9
from #Samples;
Tip: In SSMS use query results to text (Ctrl-T) for more convenient display.
You can try this, if you do not have v2012+:
DECLARE #mockup TABLE(SomeNumber INT);
DECLARE #padWidth INT=3;
INSERT INTO #mockup VALUES(-1000),(-500),(-1),(0),(1),(500),(1000);
SELECT CASE WHEN m.SomeNumber < 0 THEN '-' ELSE ' ' END
+ REPLACE(STR(ABS(m.SomeNumber),#padWidth),' ','0')
FROM #mockup AS m;
Numbers, which are to big, will be returned as ***. This is better than other approaches cutting the string with RIGHT or LEFT. They might return a bad result...
This is returned
-***
-500
-001
000
001
500
***
In DB2 this works to get a number of 15 digits including the sign:
CASE WHEN MYNUMBER < 0 THEN '-' || LPAD(MYNUMBER , 14, 0)
ELSE LPAD(MYNUMBER , 15, 0)
END

sql combining two columns one of which is a datetime

I have the following sql code (ms sql server 2008)
select (analysisno + ' ' + '-' + ' ' + description + ' ' + '-' + ' ' + formdate) as columnA
from Old_Analysis_Data
order by formdate
I get the following error Conversion failed when converting date and/or time from character string.
AnalysisNo is a varchar(10)
description is a varchar(500)
formdate is a datetime
(not my table, its an old one)
Any ideas, as cant find an answer on google.
Convert the time to a string using Convert before concatenation:
SELECT ( analysisno + ' ' + '-' + ' ' + description + ' ' + '-' + ' '
+ CONVERT(VARCHAR(20), formdate, 100) ) AS columnA
FROM
Old_Analysis_Data
ORDER BY
formdate
In this case, 100 is a style that sets datestamp format to mon dd yyyy hh:miAM (or PM) as an example
See http://www.w3schools.com/sql/func_convert.asp
Try this:
select (analysisno + ' - ' + description + ' - '
+ convert(varchar(100),formdate)) as columnA
from Old_Analysis_Data order by formdate
Instead of concatenating formdate directly, convert it to string first,
convert(varchar(15), formdate, 103)
which gives you the following format
dd/MM/yyyy

Bulk Insert Data Type Mismatch in datetime

In My Bulk Insert Query i have one of the column in .LST file as |12083121022612| Format of this column is as "YYMMDDHHMMSSTT" In dbo.ReportMain Table i have set Data Type for this as datetime
It gives me error saying that
Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 13 (DateAndTime).
Bulk Insert Code:-
BULK
INSERT dbo.ReportMain
FROM 'C:\AGS_WINCORE_120901.LST'
WITH
(
FIELDTERMINATOR = '|',
ROWTERMINATOR = '0x0A'
)
GO
Well, 12083121022612 is not a valid date:
select cast('12083121022612' as datetime)
-->
Conversion failed when converting date and/or time from character string.
You could bulk load into a staging table that uses a varchar field. You can convert the varchar field to the universal yyyy-MM-ddTHH:mm:ss:tt date format. Here's an example query that could insert rows from the staging table into the main table:
insert ReportMain
(col1)
select cast('20' + substring(col1,1,2) + '-' + substring(col1,3,2) + '-' +
substring(col1,5,2) + 'T' + substring(col1, 7,2) + ':' +
substring(col1, 9,2) + ':' + substring(col1, 11,2) +
'.' + substring(col1, 13,2) as datetime)
from ReportMain_Staging
Example at SQL Fiddle.

How do I find the count of concatenated columns of int and string data types in SQL CE?

How to merge different data type of column on SQL?
I have a table:
+-----------+-------------+
+ Column + Data Type +
+-----------+-------------+
+ Day + Int +
+ Time + Varchar +
+ Quota + Int +
+-----------+-------------+
I want to merge all of the column on that table.
I tried this but it doesn't work:
SELECT Day + ' - ' + Time + ' : ' + Quota AS [Description], COUNT(*) AS [Total]
FROM table
GROUP BY Day + ' - ' + Time + ' : ' + Quota
The error message: Data Conversion Failed. [ OLE DB status value (if known) = 2 ]
When I tried to merge only the same data type, that is: Day and Quota, it's work. How can I do that?
Columns of data type int should be converted or type cast to string data type like VARCHAR to perform string concatenation.
Click this link to view the demo in SQL Fiddle.
Script: Tested in SQL Server 2012.
CREATE TABLE dbo.MyTable
(
[Day] int NOT NULL
, [Time] varchar NOT NULL
, [Quota] int NOT NULL
);
INSERT INTO dbo.MyTable ([Day], [Time], [Quota]) VALUES
(1, '2', 101),
(1, '1', 101),
(2, '3', 101),
(2, '3', 101),
(3, '4', 263);
SELECT Description
, COUNT(Description) AS DescriptionCount
FROM
(
SELECT CAST([Day] AS VARCHAR)
+ ' - ' + Time
+ ' : ' + CAST([Quota] AS VARCHAR) AS [Description]
FROM dbo.MyTable
) T1
GROUP BY Description;
Output:
DESCRIPTION DESCRIPTIONCOUNT
----------- ----------------
1 - 1 : 101 1
1 - 2 : 101 1
2 - 3 : 101 2
3 - 4 : 263 1
UPDATE
SQL Compact Edition version of the query:
SELECT LTRIM(RTRIM(STR(Day))) + ' - ' +
LTRIM(RTRIM(Time)) + ' : ' +
LTRIM(RTRIM(STR(Quota))) AS Description
, COUNT(*) AS DescriptionCount
FROM MyTable
GROUP BY LTRIM(RTRIM(STR(Day))) + ' - ' +
LTRIM(RTRIM(Time)) + ' : ' +
LTRIM(RTRIM(STR(Quota)))
Output:
This is a mashup of my answer and Siva's, hopefully it will solve the asker's problem:
SQL Fiddle link
CREATE TABLE MyTable
(
iDay int NOT NULL
, sTime varchar(50) NOT NULL
, iQuota int NOT NULL
);
INSERT INTO MyTable (iDay, sTime, iQuota) VALUES
(1, '2', 101),
(1, '1', 101),
(2, '3', 101),
(2, '3', 101),
(3, '4', 263);
SELECT CAST(iDay AS VARCHAR) + ' - ' + sTime + ' : ' +
CAST(iQuota AS VARCHAR) AS Description
FROM MyTable
GROUP BY CAST(iDay AS VARCHAR) + ' - ' + sTime + ' : ' +
CAST(iQuota AS VARCHAR)
(Assuming MySQL):
You are trying to perform addition on strings and integers. + is not a concatenation operator in mysql. The error you get is telling you that the string could not be converted to a numeric type.
Try this:
SELECT concat(Day, ' - ', Time, ' : ', Quota) AS `[Description]`, COUNT(*) AS `[Total]`
FROM table
GROUP BY `[Description]`
When you do the GROUP BY just write the field names. So...
SELECT Day + ' - ' + Time + ' : ' + Quota AS [Description], COUNT(*) AS [Total]
FROM table
GROUP BY Day, Time, Quota
Does that work?

I can't get this error fixed : conversion failed when converting the nvarchar value

I am a newby at sql and can find the problem with my query, I am getting this error:
Msg 245, Level 16, State 1, Line 10
Conversion failed when converting the nvarchar value '00999-00-210312-11' to data type int.
Declare #Referenceid Int
SET #Referenceid = (
SELECT TOP 1 (CASE WHEN ad.ReferenceID LIKE '%NO ID%' THEN (RIGHT(MAX(ad.ReferenceID),2)+10)END)
FROM Campaign.dbo.Assets_DailyBulkImport AS ad
WHERE (ad.ReferenceID IS NOT NULL)
GROUP BY ad.ReferenceID
ORDER BY ad.ReferenceID DESC);
Select (c.Note + '' + '999' + N'-' + '00' + N'-' +
(SELECT REPLACE(CONVERT(VARCHAR(8), GETDATE(), 3), '/', '') AS MMDDYY) + N'-' + #Referenceid)
FROM Assets_DailyBulkImport AS a INNER JOIN
Controls_Profiles AS c ON a.Profile = c.Venture
where a.ReferenceID=#ReferenceID
it says that '00999-00-210312-11' is a string value you cannot convert that in integer value. as you can see - is part of data so it must be string i.e varchar its not integer value that the reason its giving error.
so to resolve you error you need to change this line
(SELECT REPLACE(CONVERT(VARCHAR(8), GETDATE(), 3), '/', '') AS MMDDYY) + N'-'
+ cast(#Referenceid as varchar(10))
in your code #Referenceid is integer value you cannot directly append it you first need to convert it like cast(#Referenceid as varchar(10))