SQL insert not inserting converted date format - sql-server

I am trying to insert records from one table into another and convert varchar to a date format with type of 101 (mm/dd/yyyy). The wierd thing that happens is that once i run stored procedure the source table data format changes but the destination shows the old format of (yyyy-mm-dd)
Any suggestions. See stored procedure below
INSERT INTO Sales
(
DEALER
,UW
,SKU
,SKU_DESCRIPTION
,EARNING_TYPE
,TERM
,PRODUCTPURCH
,CONTRACTPURCH
,ACCOUNTINGPURCH
,CONTRACTS_SUM
,PREMIUM
,RESERVE
,FEES
)
SELECT TmpSales.[DEALER]
,TmpSales.[UW]
,TmpSales.[SKU]
,TmpSales.[SKU_DESCRIPTION]
,TmpSales.[EARNING_TYPE]
,TmpSales.[TERM]
,convert(date,TmpSales.[PRODUCTPURCH], 101) as PURCHDATE
,convert(date,TmpSales.[CONTRACTPURCH], 101) as CONPURCHDATE
,convert(date,TmpSales.[ACCOUNTINGPURCH], 101) as ACCDATE
,TmpSales.[CONTRACTS_SUM]
,(TmpSales.[RESERVE] + TmpSales.[FEES]) as PREMIUM
,TmpSales.[RESERVE]
,TmpSales.[FEES]
FROM [dbo].[Tmp_Sales_Upld] as TmpSales

Related

System.Data.SqlClient.SqlException: String or binary data would be truncated

I am creating a web app in which I am executing a select command on my stored procedure, but I want to insert the same fetched data into another table.
So I tried to do something like the following
CREATE PROCEDURE profinalinstexpensesonid
(#from varchar(5000),
#to varchar(5000),
#trainer varchar(5000),
#sonvinid varchar(5000)
)
AS
BEGIN
INSERT INTO invoice(sonvinid, tid, date, brandname, zone, location, area, venuename, venue, instructore, amount)
SELECT
instructoreexpense.sonvinid,
sonvininsert.trainer,
CONVERT(VARCHAR, sonvininsert.date, 105) AS date,
sonvininsert.brandname,
SUBSTRING(sonvininsert.zone, 1, 1) AS zone,
sonvininsert.location,
sonvininsert.area,
companysonvinunitvenue.venuename,
sonvininsert.venue,
sonvininsert.instructore,
instructoreexpense.amount
FROM
instructoreexpense
LEFT OUTER JOIN
sonvininsert ON sonvininsert.sonvinid = instructoreexpense.sonvinid
AND sonvininsert.status = '0'
LEFT OUTER JOIN
finalinstructoreexpense ON finalinstructoreexpense.sonvinid = instructoreexpense.sonvinid
LEFT OUTER JOIN
companysonvinunitvenue ON companysonvinunitvenue.id = sonvininsert.comsonvinid
WHERE
sonvininsert.date BETWEEN CONVERT(DATETIME, #from, 105)
AND CONVERT(DATETIME, #to, 105)
AND sonvininsert.trainer = (SELECT empname
FROM trainerdetails
WHERE trid = #trainer)
AND instructoreexpense.sonvinid NOT IN (SELECT CAST(Item AS INTEGER)
FROM SplitString(#sonvinid, ','))
ORDER BY
instructoreexpense.sonvinid
END
and when I execute the stored procedure like
exec profinalinstexpensesonid '01-01-2013','01-01-2017','andrews'
I am getting the following error
Msg 8152, Level 16, State 13, Procedure profinalinstexpensesonid, Line 10
String or binary data would be truncated.
On my line 10 I have the following code
insert into invoice(sonvinid, tid, date, brandname, zone, location, area, venuename, venue, instructore, amount)
I don't know what is wrong here?
The error message states the size of a column in invoice table is less compared to the size of the data being inserted into it.
For example if column brandname has data type varchar(50) and you are trying to insert more than 50 characters then it will cause error.
To resolve this compare the size of columns in invoice with the size of the columns being inserted.
You need to check column size of invoice table as well as columns in select list from which you are populating data.
Let's say you are inserting column "B" having data type as varchar(70) from table2 in column "A" having data type varchar(50) in table1; this won't work as you are trying to insert 70 characters in 50 varchar sized column.
Check source & destination column data type & it's length; and change it and try again.

how to retrieve the records based on the GETDATE

I am trying to automate the task using SQL server agent to generate the report of the people who gets inserted to the table on regular basis. I have created the below stored procedure, and was trying to use same query in SQL server agent job but is not working can someone please help.
SELECT s.LAST_NAME AS sn,
RTRIM(s.FIRST_NAME)+ ' ' + LTRIM(s.LAST_NAME) AS Name,
s.FIRST_NAME AS F_Name
LEFT(middle_name,1) AS Initial,
sy.USERNAME AS USER,
s.HOME_ZIP AS ZIP,
RTRIM(UPPER(sy.USERNAME)) + LTRIM('#xyz.com') AS userP,
stm.DESCRIPTION_Maj AS company,
rg.RECORD_INPUT_DATE
FROM STCIO s
JOIN SYSME sy
ON s.ID_NUMBER =sy.ID_NUMBER
JOIN EHMGR rg
ON s.ID_NUMBER =rg.ID_NUMBER
JOIN STMEER stm
ON rg.MAJOR =stm.MAJOR
AND s.MAT_CODE IN ('','G','Q')
AND rg.CURRENT_FLAG = 'X'
AND CONVERT(datetime,CONVERT(CHAR(8),rg.RECORD_INPUT_DATE)) = GETDATE()
NOTE:datatype for Record_input_date is numeric(8,0)
Error message received is
"Arithmetic overflow error converting expression to data type datetime."
I don't have an authority to make any changes. All I'm looking for is to have this query running converting the record_input_date (numeric) to datetime and populate the record based on the getdate()
Now this would happen if you still have the date stored as numeric in a wrong format (non ANSI format)
Like instead of 20160307 for today's date it stores it as 20160703 in which case it will give error for values like 20162002 or when the date is stored as ddmmyyyy or any other variant format. To solve look at some sample data and tweak your query from
CONVERT(datetime,convert(char(8),rg.RECORD_INPUT_DATE)) = GETDATE()
to
CONVERT(datetime,convert(char(8),rg.RECORD_INPUT_DATE),<formatstring>) = GETDATE()
See list of format strings here
Another way is to use date from parts function in higher version of sql server like
SELECT DATEFROMPARTS(RECORD_INPUT_DATE / 10000,
RECORD_INPUT_DATE % 100,
(RECORD_INPUT_DATE/ 100) % 100) AS YR_MNTH_DT
If you cannot use either of above, you'll have to isolate days,months and year from the number.
Example if your number is wrong format like ddmmyyyy (03062016)
DECLARE #dd INT, #mm INT, #yyyy INT, #newdate INT
SET #dd= RECORD_INPUT_DATE/1000000 --3
SET #mm= (RECORD_INPUT_DATE/10000) %100--6
SET #yyyy= (RECORD_INPUT_DATE) % 10000--2016
SET #newdate= #yyyy*10000+#mm*100+#dd
and use this #newdate for comparison
CONVERT(datetime,convert(char(8),#newdate)) = GETDATE()
Step 1 is turning this wall of text query into something you can read.
SELECT s.LAST_NAME AS sn
, RTRIM(s.FIRST_NAME) + ' ' + LTRIM(s.LAST_NAME) AS Name
, s.FIRST_NAME AS F_Name
, LEFT(middle_name, 1)AS Initial
, sy.USERNAME AS [USER]
, s.HOME_ZIP AS ZIP
, RTRIM(UPPER(sy.USERNAME)) + '#xyz.com' AS userP
, stm.DESCRIPTION_Maj AS company
, rg.RECORD_INPUT_DATE
FROM STCIO s
JOIN SYSME sy ON s.ID_NUMBER = sy.ID_NUMBER
JOIN EHMGR rg ON s.ID_NUMBER = rg.ID_NUMBER
JOIN STMEER stm ON rg.MAJOR = stm.MAJOR
AND s.MAT_CODE in ('', 'G', 'Q')
AND rg.CURRENT_FLAG = 'X'
AND CONVERT(DATETIME, CONVERT(CHAR(8), rg.RECORD_INPUT_DATE)) = GETDATE()
The problem here is that you have an integer that is not able to be converted to a datetime value. This is an inherent problem of using improper datatypes. You are likely going to be forced to drop the date condition from this query and replace it with an ISDATE. Insert those results to a temp table. Then another query to pull from the temp table with your date predicates.

How to change date-time format?

I have a RegDate column of nvarchar(max) type in my table in which dates are stored in mm/dd/yyyy (5/22/2015 11:09:39 PM) and dd-mm-yyyy (19-05-2015 22:55:05) format. I want to get all these entries in one format i.e. dd/mm/yyyy. I tried to convert it by using
Convert(varchar(10),cast(vr.RegDate as DATETIME),105) as RegistrationDate
but it gives following error:
The conversion of a nvarchar data type to a datetime data type resulted in an out-of-range value.
Please help me regarding this problem.
You need to determine the format of the value you are converting before you can convert it. If it's simply between those two formats, you can simply search for - to determine it's format.
I would also suggest storing the value in a datetime column as opposed to a varchar, and if you can't do that for whatever reason, you should definitely store it in an ISO format: YYYY-MM-DD HH:MM:SS.
Here's a sample that uses a case statement to provide optional formatting of your two date formats, using the presence of the - character:
CREATE TABLE #temp ( RegDate VARCHAR(50) )
INSERT INTO #temp
( RegDate )
VALUES ( '5/22/2015 11:09:39 PM' ),
( '19-05-2015 22:55:05' )
SELECT CASE WHEN CHARINDEX('-', RegDate) != 0
THEN CONVERT(DATETIME, RegDate, 105)
ELSE CONVERT(DATETIME, RegDate, 101)
END AS FormattedToDate
FROM #temp
DROP TABLE #temp
Produces:
FormattedToDate
2015-05-22 23:09:39.000
2015-05-19 22:55:05.000

Get data after year 2012 SQL Server

I am trying to get data after year 2012.
Date is saved in nvarchar format in a table. For example: 12/31/2010
Column also has some other values like 'Confidential', I don't want this row.
I am trying a query (shown below) but it is not succeed :-
select *
from tbl_ProductionWells
where CONVERT(NVARCHAR(10), wellstatusdate, 103) > CONVERT(NVARCHAR(10), '01/01/2012', 103)
Edited :-
I tried this :-
SELECT *
FROM tbl_ProductionWells
WHERE DATEPART(YEAR, CAST(wellstatusdate AS date)) > 2012
But it is giving an error (shown below), This column also has some text values like 'not available','Confidential' .. :-
Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.
Note:- I can't change column datatype as it also contains some other texts.
Thanks in advance
First of all: Store date values in DATE columns, datetimes in DATETIME2 columns. Always choose proper data type for your data
You have to convert your NVARCHAR to DATE, then compare it to 2012-01-01
OR you can extract the 'year' part of your string.
SELECT *
FROM tbl_ProductionWells
WHERE CONVERT(DATE, wellstatusdate) >= '2012-01-01'
The best choice is to change your column's data type to DATE. After that, you can do lots of magicial things with those values. Store the 'Confidental' flag in another column.
EDIT
Some additional info:
Please note, that the STRING -> DATE conversion depends on the current session's language.
Run this batch to see the difference:
DECLARE #DateAsChar VARCHAR(32) = '01/02/12';
SET LANGUAGE us_english
SELECT CONVERT(VARCHAR(32), CONVERT(DATE, #DateAsChar), 120)
SET LANGUAGE Hungarian
SELECT CONVERT(VARCHAR(32), CONVERT(DATE, #DateAsChar), 120)
SET LANGUAGE Deutsch
SELECT CONVERT(VARCHAR(32), CONVERT(DATE, #DateAsChar), 120)
How about:
WITH cte
AS ( SELECT *
FROM tbl_ProductionWells
WHERE ISDATE(wellstatusdate) = 1
)
SELECT *
FROM cte
WHERE DATEPART(YEAR, CAST(wellstatusdate AS DATE)) > 2012
Select all data from the table that is a date using IsDate, then work with that dataset only.
SELECT * FROM
(SELECT * FROM tbl_ProductionWells WHERE ISDATE(wellstatusdate) = 1)
WHERE CAST(wellstatusdate as Date) > #YOURDATE

time format in SQL Server

Does anyone know how can I format a select statement datetime value to only display time in SQL Server?
example:
Table cuatomer
id name datetime
1 Alvin 2010-10-15 15:12:54:00
2 Ken 2010-10-08 09:23:56:00
When I select the table I like the result will display as below
id name time
1 Alvin 3:12PM
2 Ken 9:23AM
Any way that I can do it in mssql?
You can use a combination of CONVERT, RIGHT and TRIM to get the desired result:
SELECT ltrim(right(convert(varchar(25), getdate(), 100), 7))
The 100 you see in the function specifies the date format mon dd yyyy hh:miAM (or PM), and from there we just grab the right characters.
You can see more about converting datetimes here.
You can use the CONVERT function like this:
SELECT CONVERT(varchar, your_datetime, 108)
However, this is 24-hour clock, no AM/PM.
This will get the time from a datetime value and also give the am or pm add on
SELECT RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,getDate(),100),8)),7)
will always return the date in HH:mmAM format.
Note the lack of space
Or
SELECT REPLACE(REPLACE(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,getDate(),100),7)),7),'AM',' AM'),'PM',' PM')
will always return the date in HH:mm AM format.
Hope that helps.
PK
Try:
select convert(varchar, getdate(), 108)
+ ' ' + RIGHT(convert(varchar, getdate(), 100), 2) as Time
You might be able to use:
select
convert(varchar,getdate(),114)
You might be able to manually construct the query like:
string query = string.Format("INSERT INTO test (DateOnlyField, TimeOnlyField) VALUES ('{0}', '1899-12-30 {1}')", DateTime.Today.ToShortDateString(), TimeString)
I dunno if this might work to:
Create Table Schedule( ScheduleID Integer Identity, ScheduledTime DateTime )
Go
Insert Into Schedule( ScheduledTime ) Values( '10:15:00 AM' )
Go
Select ScheduledTime As DBScheduledTime, Convert( VarChar( 10 ), ScheduledTime, 114 ) As ScheduledTime
From Schedule
Go
Drop Table Schedule
Go
If You are using SQL Server 2008 or Higher You can use the following statement:
SELECT Convert( VarChar( 10 ), CAST([columnName] AS TIME(0)), 100 )
If you are using MySql
you can use TIME_FORMAT()
Code ↓↓
SELECT name, time_format(datatime,'%H:%i') as tine from cuatomer

Resources