View failing on data conversion - SQL Server - 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

Related

Casting an inserted string to a date in the same insert

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.

Conversion failed when converting the varchar value 'Netlover Broadband' to data type int

CREATE VIEW Customer_view
as select customerID, first_name, last_name, DOB, contact_number, customer_address, Customer_email, joined_date,convert(int,c.Plan_Name) as 'mega plan'
from Customer as c, MegaPlan as m, ACCESS as a
where c.Plan_Name=m.Plan_Name and c.Plan_Name = a.AccessID
I'm trying to create a view which shows all details of all customers, mega plan and access type
How can I fix this
I think c.Plan_Name column datatype is varchar(n) and it contains some text value that why showing error. Don't convert it into integer.

Convert to mm/dd/yyyy and select max value

Using SQL Server 2014, I have a date field named LAST_BASELINE_UPDATE_DATE that is stored as datetime.
I used the CONVERT function to convert to mm/dd/yyyy:
convert(date,LAST_BASELINE_UPDATE_DATE,101) as BASELINE_UPDATE_DATE
What I want to be able to do is then select the MAX value of BASELINE_UPDATE_DATE without creating a table. Is this even possible?
It's a little unclear from your post what your data is and what you're trying to get out. Here are a couple solutions, hopefully one of which is applicable
Assuming you want your result as a string formatted mm/dd/yyyy you can do this
select convert(varchar(10), max(LAST_BASELINE_UPDATE_DATE), 101))
from YourTable
If you just need it as a date, just do
select max(LAST_BASELINE_UPDATE_DATE)
from YourTable
if LAST_BASELINE_UPDATE_DATE is already a string (formatted mm/dd/yyyy) and you want it as a date,
select max(convert(date, LAST_BASELINE_UPDATE_DATE, 101))
from YourTable
I think you are complicating this. Just do the conversion on the max datetime values.
declare #table table (LAST_BASELINE_UPDATE_DATE datetime)
insert into #table
values
('20160701 12:21'),
('20160705 03:21'),
('20160401 19:21'),
('20161201 04:21')
select
convert(varchar(10),max(LAST_BASELINE_UPDATE_DATE),101)
from
#table
This method converts your single returned row, which is the max() value of your datetime columns, as opposed to converting every row and then finding the max value.

Selecting datetime from SQL Server?

I'm selecting a date from SQL Server, but having an issue. If I inserted the data as 06/06/2012, it gets saved in this format in SQL Server. When I SELECT it from the table, it looks like 6/6/2012.
I tried to use this:
SELECT
FirstName, LastName,
CONVERT(VARCHAR, DOB, 101)
FROM
TblClients
but I get an error:
ITEM cannot be found in the collection corresponding to this name or ordinal.
Sounds like your VB code is fine until you don't return the expected "ITEM".
Try aliasing your convert with the column name:
SELECT FirstName, LastName, convert(varchar,DOB, 101) AS DOB From TblClients
What I needed to do is compare the value from tblClients and value from a mskDOB.text. So what I did is I converted both to string, formatted them in this way--> "YYYYMMDD", compared them and it works.

create a dummy column and populate with select

I need to use a select query to create a dummy column and pad it with a constant value. I found a partial answer to my question in a related post, here was the answer:
select name, address, 'No' as vacationing, Zipcode from mytable;
My question is what do you do if you want to pad it with a number, such as:
'9999' AS vacationing - I get an error with that
Also, what if I want the cell to be empty, such as;
'' AS vacationing - I get an error here also
TIA
'9999' AS vacationing is perfectly valid.
you must be using union with different column type - hence error.
SELECT name, address, '9999' AS vacationing, Zipcode FROM mytable;
And:
SELECT name, address, '' AS vacationing, Zipcode FROM mytable;
Are both valid T-SQL queries. You don't say what error you're getting, but neither of these should throw an error.

Resources