Prefix 0 in a Phone number string SQL - sql

I have a phone number in sql table, i want to add prefix '0' where ever phone number is 10 digit,
but if it is less than 10 or greater than 10 digit then no 0 prefix required.
7863176061
7724269820
2088076157
1992762084
1318912
output
07863176061
07724269820
02088076157
01992762084
1318912

Try this
SELECT CASE LEN(Num) WHEN 10 THEN '0'+cast(Num as varchar(11)) ELSE Num END AS Num

Try this:
select
case when len(yourcolumn) =10
then '0'+ yourcolumn
else yourcolumn end as column
from yourtable

Use CASE expression to check the length.
Query
select
case when len([phone_number]) = 10
then '0' + cast([phone_number] as varchar(20))
else cast([phone_number] as varchar(20)) end
from [your_table_name];
Find demo here
You have to cast the phone number column to varchar if the column datatype is in bigint. Otherwise you can exclude the cast part in the above query.

i think this will be fast,
select
'0' + cast([phone_number] as varchar(20))
from [your_table_name]
where len([phone_number]) = 10 ;

Related

Converting varchar to int (a strange case?)

I have scoured through all "Varchar to Int" posts but can't seem to find anyone with this issue (although, I am fairly new to SQL so I may be doing something fundamentally wrong):
SELECT *
FROM [TABLE]
WHERE CONVERT(INT,
CASE
WHEN NOT CONVERT(VARCHAR(12), dept_code) LIKE '%[^0-9]%' THEN 8900
END) < 9000;
It's a fairly simple query, where the goal is to filter out all the values in field "dept_code" so that only fully numeric values less than 9000 are kept; varchars and non-numeric values are fine to stay. When running the above I still get the error "Conversion failed when converting the varchar value 'E103' to data type int."
Any help would be appreciated.
You can simply this query by avoiding CASE and Regex like expression. You can use IsNumeric function to filter numeric rows and then apply the condition by converting dept_code of filtered rows to int, like below -
select * from tablex
where ISNUMERIC(dept_code) = 0 --alphanumeric code
OR(ISNUMERIC(dept_code) = 1 and Convert(int, dept_code) < 9000) -- numeric less than 9000
Example here
Use try_convert() or try_cast():
SELECT t.*
FROM [TABLE] t
WHERE TRY_CONVERT(int, dept_code) < 9000
If you want to speed this query, you can materialize a computed column and add an index:
alter table [table] add dept_code_int as (try_convert(int, dept_code)) persisted;
create index idx_table_dept_code_int on [table](dept_code_int);
You are missing an else in your case statement ... Secondly do your numeric dept_codes get to be really big ... this thing will choke on that.
SELECT *
FROM [TABLE]
WHERE CONVERT(INT,
CASE
WHEN NOT CONVERT(VARCHAR(12), dept_code) LIKE '%[^0-9]%' THEN 8900 ELSE dept_code
END) < 9000;
Try this: http://sqlfiddle.com/#!18/bb6b7/17
;WITH TABLE_ENHANCED AS
(
SELECT
t.*
, dept_code_numeric =
CASE
WHEN CONVERT(VARCHAR(12), dept_code) NOT LIKE '%[^0-9]%'
THEN CONVERT(INT, dept_code)
ELSE 0
END
FROM [TABLE] t
)
SELECT
*
FROM TABLE_ENHANCED
WHERE dept_code_numeric < 9000
Try below Script
SELECT *
FROM [TABLE]
WHERE isnumeric(dept_code)=1
and dept_code<9000;
This should work. The conversion to int is implicit.
SELECT *
FROM test
WHERE (ISNUMERIC(dept_code)=1 and dept_code<9000)
or (ISNUMERIC(dept_code) = 0)

How to sort a column in ascending order where the column contains varchar and numeric, using SQL?

Actually my column is in varchar, and it has numeric and varchar type data, i just wanted to sort numeric first then varchar type.
I refered and got this:
SELECT
...
ORDER BY
CASE
WHEN ISNUMERIC(value) = 1 THEN CONVERT(INT, value)
ELSE 9999999 -- or something huge
END,
value
It works, but why we need to use ELSE 9999999 here, instead what we can replace...?
Any solution for this...!
You could use:
SELECT *
FROM tab
ORDER BY IIF(TRY_CAST(val AS INT) IS NULL, 1, 0),TRY_CAST(val AS INT);
DBFiddle Demo
You can try this as an alternative solution.
SELECT
...
ORDER BY
ISNUMERIC(value) DESC
, CASE
WHEN ISNUMERIC(value) = 1 THEN CONVERT(INT, value)
END
,value

Group Numbers based on Level

I have requirement in SQL Server database where I have to group the data. please find the image attached for reference.
If the Level is more than 2 then it has to be grouped under level 2 (ex: 1.1.1, 1.1.2 are rolled up under 1.1.) and if there isn't any level 2 available then have to create a second level based on the level 3 Numbers (ex: 1.2.1)
Thanks
If it's not certain that the first 2 numbers are single digits:
declare #T table ([Column] varchar(20));
insert into #T values ('1'),('1.2.'),('1.2.3.'),('1.2.3.4.'),('10.20.'),('10.20.30.'),('10.20.30.40.');
select
case when [Column] like '%.%.%' then substring([Column],1,charindex('.',[Column],charindex('.',[Column])+1)) else [Column] end as [Derived Col1],
case when [Column] like '%.%.%.%' then [Column] else '' end as [Derived Col2]
from #T;
If it's certain that the first 2 numbers are single digits then it can be simplified:
declare #T table ([Column] varchar(20));
insert into #T values ('1'),('1.2.'),('1.2.3.'),('1.2.3.4.');
select
substring([Column],1,4) as [Derived Col1],
case when [Column] like '%.%.%.%' then [Column] else '' end as [Derived Col2]
from #T;
you can use CHARINDEX to locate '.' and then decide DERIVED_COL_2.
SELECT COLUMN,
SUBSTRING(COLUMN,1,4)DERIVED_COL_1,
CASE WHEN CHARINDEX('.',COLUMN,5) = 6 THEN COLUMN END AS DERIVED_COL_2
FROM YOUR_TABLE
Would this do, if you need the new values as computed columns?
Updated: this works with double digits and the third column is null for 1st/2nd level version
CREATE TABLE Test
(
Version varchar(30),
VersionMain AS CASE
WHEN CHARINDEX('.',Version,4) > 0 THEN LEFT(Version,CHARINDEX('.',Version,4)) ELSE Version END,
VersionSub AS CASE
WHEN LEN(Version) - LEN(REPLACE(Version,'.','')) >= 3 THEN Version ELSE NULL END
)

Retrieve Individual character from varchar field in SQL Server

How can I retrieve individual characters of field values (e.g A - C - D from value ACD) and manipulate in SQL Server if I have a column of type varchar(4) with following variable length values.
Column
---
ACD
BC
CD
Thanks
select case when CHARINDEX('A', columnName, 1) > 0 then 1 else 0 end has_a,
case when CHARINDEX('B', columnName, 1) > 0 then 1 else 0 end has_b,
case when CHARINDEX('C', columnName, 1) > 0 then 1 else 0 end has_c,
case when CHARINDEX('D', columnName, 1) > 0 then 1 else 0 end has_d
from tableName
You may use SUBSTRING:
SELECT SUBSTRING('ABC',1,1)
The first param is the input string, the second one is the start index 1-based, and the third is the length of the result.
So if you have a column Col1 in a table Table1:
SELECT SUBSTRING(Col1,1,1),
SUBSTRING(Col1,2,1),
SUBSTRING(Col1,3,1),
SUBSTRING(Col1,4,1)
FROM Table1
You will get an empty string if for instance you have three characters and you try to get the fourth.
Fiddle Example Here

Number of numeric values present in NVarchar column in SQL Server 2005

I have a Nvarchar column which contains data related to different data types such as Numerics, Dates and so on.
I wanted to find out number of cells with Numeric data type and number of cells with Date data type.
Thanks
It looks like you just want IsDate() and IsNumeric():
SELECT Sum(CASE WHEN IsDate(DataColumn) = 1 THEN 1 ELSE 0 END) AS Dates,
Sum(CASE WHEN IsNumeric(DataColumn) = 1 AND IsDate(DataColumn) = 0 THEN 1 ELSE 0 END) AS Numbers
FROM YourTable
This is assuming that you have a single date format, and that that format is supported by SQL Server's dateformat option. To define the correct format, you would use SET DateFormat. See MSDN Documentation on IsDate.
You mention that '20041201' could be a valid date, which is why I added the extra IsDate() check in the numeric count (I assume you wouldn't want to count it as both a date and a number).
First at all you should split you column (create split function which will transform delimited string into column) . You can find a lot of examples in Internet. I have got one here . So here is an example:
declare #text nvarchar(max)='1211221,ssssss,1212,2010-02-01,20100201'
DECLARE #delimiter char(1)=','
;WITH Pieces(pn, start, stop) AS (
SELECT CASt(1 as Int), CAST(1 as integer), CHARINDEX(#delimiter,#text)
UNION ALL
SELECT pn + 1, CAST(stop + 1 as integer), CHARINDEX(#delimiter,#text, stop + 1)
FROM Pieces
WHERE stop > 0
), T as(
SELECT pn,
SUBSTRING(#text, start, CASE WHEN stop > 0 THEN stop-start ELSE 512 END) AS s
FROM Pieces)
SELECT
SUM(CASE WHEN ISNUMERIC(T.s)=1 AND ISDATE(T.s)=0 THEN 1 ELSE 0 END) NumericCount,
SUM(CASE WHEN ISDATE(T.s)=0 THEN 0 ELSE 1 END)DateCount
FROM T
You will have 2 dates and 2 numeric counts