Casting an inserted string to a date in the same insert - sql-server

SQL Server 2017 - although this post is quite old, I still referred to it: Using cast in insert statement (the answer with 6 votes), but I'm getting an error when trying to perform this simple INSERT statement:
INSERT INTO dbo.Table (Name, DateOfBirth, DateOfBirth_Normalized)
VALUES ('John Doe', '1943-09-08', CAST(DateOfBirth AS DateTime))
The error I'm getting is that the DateOfBirth inside the CAST statement is an invalid column name.
How can I achieve this?
FYI, DateOfBirth is nvarchar(50) and DateOfBirth_Normalized is DateTime.
EDIT 1: this is for a stored procedure, so the DateOfBirth value will be different for every INSERT and therefore can not simply be passed as the string value, as suggested in the comments.

Related

View failing on data conversion - SQL Server

I need help redesigning a view. Currently it is giving an error when you do a simple select of the view. The error is as follows.
Error converting data type nvarchar to bigint
This is the current design of the view.
SELECT
FirstName,
MiddleName,
LastName,
CONVERT(bigint, SUBSTRING(Reference, 2, 10)) AS LogNum,
Address,
Birthday,
Gender,
BirthDate,
Gender,
ClientCode
FROM
dbo.Client
WHERE
(Reference LIKE 'C%')
The issue is happening because the reference column which has a nvcarchar(16) datatype has values that are as follows.
'C3456423445'
'2234567310'
'C8921244532'
The substring function basically strips out the "C" and returns the 10 digit numbers after it as a bigint.
What is happening now is there is new data that came into the client table that has values for reference column as follows
"CC4309842387"
"CC29383761760"
Since there is an extra C in the new values, the function is not doing its job.
I need to redesign the view so that it can handle both iterations of the values in the reference column. What is essential is the 10 digit numbers coming out intact for the front end report.
Thank you for your help.
If there are only two options "C" and "CC", then you can use REPLACE with LEFT instead of SUBSTRING.
SELECT
FirstName,
MiddleName,
LastName,
Convert(bigint,Left(Replace(Reference, 'C',''),10)) AS LogNum,
Address,
Birthday,
Gender,
BirthDate,
Gender,
ClientCode
FROM dbo.Client
WHERE (Reference LIKE 'C%')
If other than preceding C's, you can use patindex() to find the position of the 1st numeric
Also, I prefer try_convert() because if the conversion fails, it will return a NULL rather than throwing an error.
Example
Declare #YourTable Table ([Reference] nvarchar(50)) Insert Into #YourTable Values
('C3456423445')
,('2234567310')
,('C8921244532')
,('CC29383761760')
,('XX29383761760')
Select *
,NewValue = try_convert(bigint,substring([Reference],patindex('%[0-9]%',[Reference]),25))
from #YourTable
Results
Reference NewValue
C3456423445 3456423445
2234567310 2234567310
C8921244532 8921244532
CC29383761760 29383761760
XX29383761760 29383761760

SQL server date conversion - 'Conversion failed'

I have problem with converting date from varchar to date format:
Msg 241, Level 16, State 1, Line 15
Conversion failed when converting date and/or time from character string.
I'm trying to convert/cast it like SELECT convert(DATE, '25.02.2019');. Can't change string order bacause the data are from existing table.
I know that the solution is easy but I'm still missing something and didn't get it yet :(
If you are unable to fix the underlying problem (that the table uses the wrong data type), you need to apply the correct DATETIME Style, which for dd.MM.yyyy is 104:
SELECT CONVERT(DATE, '25.02.2019', 104);
If at all possible though you should correct the original table. You should never store dates using VARCHAR, there is not one good reason to do so, and lots of good reasons not to. It will save you a lot of headaches if you change your datatype to DATE and then you won't have to worry about conversion errors. The longer you leave it the worse it will get. If you can't change the table, have a word with your DBA, and tell them to change the table. If you don't have a DBA, find someone who can.
Some good articles on this below:
Bad habits to kick : choosing the wrong data type
Bad habits to kick : mis-handling date / range queries
ADDENDUM
If you are unable to change the actual column because it is used by other processes, you can still sanitise the column by using a check contraint, and optionally include a computed column so you always have access to a real date, and not a varchar:
e.g.
IF OBJECT_ID(N'tempdb..#DateTest', 'U') IS NOT NULL
DROP TABLE #DateTest;
CREATE TABLE #DateTest
(
StringDate CHAR(10) NOT NULL,
RealDate AS CONVERT(DATE, StringDate, 104),
CONSTRAINT CHK_DateTest__RealDate CHECK (TRY_CONVERT(DATE, StringDate, 104) IS NOT NULL)
);
This will allow you to continue to add/edit varchar dates:
-- insert valid date and check output
INSERT #DateTest (StringDate) VALUES ('25.02.2019');
SELECT RealDate
FROM #DateTest;
The check constraint will prevent you from adding any dates that are not dates:
--Try to insert invalid date
INSERT #DateTest (StringDate) VALUES ('29.02.2019');
This will throw an error:
The INSERT statement conflicted with the CHECK constraint "CHK_DateTest__RealDate". The conflict occurred in database "tempdb", table "dbo.#DateTest___________________________________________________________________________________________________________000000000704", column 'StringDate'.
You can even index the column:
CREATE NONCLUSTERED INDEX IX_DateTEst ON #DateTest (RealDate);
With the index on you can take advantage of the benefits storing dates properly gives.
Your string is in the wrong format.
Should be:
SELECT convert(DATE, '2019-05-02')
Edit: If you can't get the date in that format, put 104 as a third argument.
Here's a list of the optional format arguments. https://www.w3schools.com/SQL/func_sqlserver_convert.asp

Cannot insert 'NULL' value into SQL Server column

I have a table that is filled using a stored procedure. This stored procedure uses a view that calls attributes from another databases.
To illustrate, it is something like:
ALTER PROCEDURE theSp
AS BEGIN
INSERT INTO dbo.theTable (attr1, att2, amount, attr4)
SELECT attr1, attr2, amount, attr4
FROM theView
END
The view is defined this way:
select attr1, attr2, amount, attr4
from db1.theTable
where date >='anyDate'
and the values are correctly inserted, but if the view is used this way:
select attr1, attr2, amount, attr4
from db2.theTable
where date >='anyDate'
this message is shown:
Checking identity information: current identity value '1252'.
DBCC execution completed. If DBCC printed error messages, contact your system administrator.
Msg 515, Level 16, State 2, Procedure theSp, Line 16
Cannot insert the value NULL into column 'amount', table 'db2.dbo.theTable'; column does not allow nulls. INSERT fails.
Note: the 'amount' attribute for db1 and db2 tables allows null but I never insert null, instead, I insert 0.
So I filtered to check whether the amount attribute is null and I did not get results, meaning there are not nulls value in the amount attribute.
Does anyone know a possible solution?
By looking at the error message that you have posted
Cannot insert the value NULL into column 'amount', table 'db2.dbo.theTable'; column does not allow nulls. INSERT fails. The statement has been terminated.
there is a Null value for amount column in `db2.dbo.theTable'. You can use ISNULL() to get rid of this issue.
If you want to see the NULL values, you gotta use query like
select * from db2.dbo.theTable where amount IS NULL
Have a look at is Null vs =Null to see why you weren't seeing those null records in your previous query.
Good to have a logger to validate the condition when it's going wrong, like printing the values before inserting

save string to a date field in sql server

I have the following string that I need to save to a sql server database column that has a date datatype.
'2017-05-25T00:00:00'
Can I use cast within a insert script to save this value and is this the best way?
yes You can insert the value like this
INSERT INTO YourTable(ColumnName)
SELECT CAST(StringFiled AS DATETIME)
You Can cast it as Date,DateTime or any other Date type you need
You can use any of the following options.
insert into myTable
values (CAST('2017-05-25T00:00:00' as datetime))
insert into myTable
values (Convert(varchar(30),'2017-05-25T00:00:00',102))

Not able to populate a table from the output of a function

I am unable to populate my table from the output of my function. I have three columns in my table namely, EmpId,Dates,EmpName. The columns EmpId and EMpName are static values which are getting populated fine but the column Dates has to be populated through a function. However, when I try to do the same I am getting a syntax error.
Please Find below the query I am using
INSERT INTO Dbo.LeaveDates (EmpId,[Date],EmpName) VALUES(#EmpId,MyDate,#Emp_Name)
Select MyDate from [dbo].[ListDates](CONVERT(CHAR, #FromDate),CONVERT(CHAR, #ToDate))
The error I am getting is also under:
*The name "MyDate" is not permitted in this context. Valid expressions are constants, constant expressions, and (in some contexts) variables.
Column names are not permitted.
*
I have declared all variables in question
What am I doing wrong?
You have to do it this way:
INSERT INTO Dbo.LeaveDates (EmpId,[Date],EmpName)
SELECT #EmpId, MyDate, #Emp_Name
FROM [dbo].[ListDates](CONVERT(CHAR, #FromDate),CONVERT(CHAR, #ToDate))
Your query consists essentially of two separate sql statements. An INSERT INTO:
INSERT INTO Dbo.LeaveDates (EmpId,[Date],EmpName)
VALUES(#EmpId,MyDate,#Emp_Name)
followed by a SELECT:
SELECT MyDate
FROM [dbo].[ListDates](CONVERT(CHAR, #FromDate),CONVERT(CHAR, #ToDate))
INSERT fails because, as the error message clearly states, MyDate is not permitted in this context, i.e. as a separate column name, without being selected from a table.

Resources