How to format numeric value when casting to varchar? - sql

I have query similar to this:
DECLARE #value decimal(8,0) = 1
SELECT (CAST #value AS varchar(8))
How can I get output formatted with leading zeros (00000001, 00000023, 00000623 etc.)?
How can I do that?
It is simple task in .Net or Java, but I must do it inside view.

This should work:
DECLARE #value decimal(8,0) = 1
SELECT RIGHT('0000000' + CAST(#value AS varchar(8)), 8)

Try this
SELECT RIGHT('00000000' + CAST (#value AS varchar(8)),8)

try this:
declare #value varchar(8)='623';
Select ltrim(right(replicate(0,8) + CAST (#value AS varchar(8)),8))
SQL Fiddle demo

try this:
DECLARE #value decimal(8,0) = 1
SELECT REPLICATE('0',8-len(#value))+CAST(#value AS varchar(8))

You can use REPLICATE and RIGHT to do this, like so:
SELECT RIGHT(REPLICATE('0', 8) + CAST(#valueAS VARCHAR(8)), 8)
Live Demo

Related

Removing zeros after a dash

I have data in a column formatted like:
012345-0001
001234-0011
123456-0111
000012-1234
i need a query to return the data like:
012345-1
001234-11
123456-111
000012-1234
i have created a function to remove a varying number of leading zeros, but can't figure out how to do it after the dash.
Thanks for any assistance
Function:
DECLARE #Output varchar(8000), #Value int, #Input varchar(8000)
SELECT
#Value = CASE
WHEN #Input LIKE '%[A-Z]%' THEN -1
ELSE CONVERT(int, RIGHT([matcode], 4))
END
FROM matter
WHERE matcode = #Input
IF (#Value = -1) SET #Output = #Input
ELSE IF (#Value BETWEEN 1 AND 999) SET #Output = RIGHT('000' + CONVERT(varchar(3), #Value), 3)
ELSE IF (#Value BETWEEN 1000 AND 9999) SET #Output = RIGHT('0000' + CONVERT(varchar(4), #Value), 4)
ELSE SET #Output = #Input
RETURN #Output
This should work, but can't test it..
DECLARE #Output varchar(8000), #Value int, #Input varchar(8000)
SELECT
#Value = CASE
WHEN #Input LIKE '%[A-Z]%' THEN -1
ELSE CONVERT(int, RIGHT([matcode], 4))
END
FROM matter
WHERE matcode = #Input
IF (#Value = -1) SET #Output = #Input
ELSE SET #Output = CONCAT( LEFT(#Input, 7), #Value )
RETURN #Output
Use below code to get the result.
select substr('001234-0011', 0, instr('001234-0011', '-') ) ||
replace(substr('001234-0011', instr('001234-0011', '-')+1), '0', '') from dual;
Use this if SqlServer as you have mentioned tSql
select substring('001234-0011', 0, CHARINDEX('-', '001234-0011')) + replace(substring('001234-0011', CHARINDEX('-', '001234-0011'), 10), '0', '')
The example below simply uses a CASE and a LIKE to check if the string ends with dash and 4 digits .
And a concat of an INT doesn't add leading zero's.
declare #Table table (col varchar(30));
insert into #Table (col) values
('012345-0001'),
('001234-0011'),
('123456-0111'),
('000012-1234');
select col as [in],
(case
when col like '%-0[0-9][0-9][0-9]'
then concat(left(col,len(col)-4), cast(right(col,4) as int))
else col
end) as [out]
from #Table;
Returns:
in out
012345-0001 012345-1
001234-0011 001234-11
123456-0111 123456-111
000012-1234 000012-1234
A test here
Using the varchar variables it could be used like this:
DECLARE #Input varchar(30), #Output varchar(30);
SET #Input = '012345-0001';
SET #Output = case when #Input like '%-0[0-9][0-9][0-9]' then concat(left(#Input,len(#Input)-4), cast(right(#Input,4) as int)) else #Input end;
Try this:
declare #var varchar(30)
set #var = '012345-0021'
select concat(
left(#var,charindex('-',#var)-1), --keeps first side 'as is'
'-',
right( --for the second part
right(#var,charindex('-',reverse(#var))),
charindex( '0', reverse(right(#var,4)) )-1 --finds the position first '0' of the reversed string (the last 0)
)
) as output
output: 012345-21
Try it on db<>fiddle: link
Yet another option is use use parsename() with a concat
Example
Select *
,NewValue = concat( left(YourCol,charindex('-',YourCol+'-') )
,try_convert(int,parseName(replace(YourCol,'-','.'),1))
)
from YourTable
Returns
YourCol NewValue
012345-0001 012345-1
001234-0011 001234-11
123456-0111 123456-111
000012-1234 000012-1234
I noticed that most of the solutions assume that the each part of the text which is seems like a number, is on the length of 4 char.
Here is another solution Based on PARSENAME function which is a bit more flexible:
declare #Table table (col varchar(30));
insert into #Table (col) values
('012345-0001'),
('001234-0011'),
('123456-0111'),
('000012-1234')
SELECT
PARSENAME(REPLACE(col,'-','.'), 2) +
'-' +
CONVERT(VARCHAR(10), CONVERT(INT, PARSENAME(REPLACE(col,'-','.'), 1)))
FROM #Table
What about a one-liner using XQuery:
DECLARE #mockup TABLE (YourValue VARCHAR(30));
INSERT INTO #mockup VALUES
('012345-0001'),
('001234-0011'),
('123456-0111'),
('000012-1234');
--This is the query
SELECT YourValue
,CAST('<x>' + REPLACE(YourValue,'-','</x><x>') + '</x>' AS XML)
.value('concat(/x[1],"-",string(xs:int(/x[2])))','varchar(30)')
FROM #mockup;
The query will first transform your 012345-001 into <x>012345</x><x>001</x> with simple string replacements. The actual magic is happening within the XQuery expression.

Convert time interval into decimal hours in SQL Server

I have a time interval in the format '88:52:57'
I need to convert it into a decimal hours in the format 88.88
How can I do this?
I have the data initially loaded as a varchar
You can use left, right and substring to extract the values and then do some calculations.
declare #S varchar(8) = '88:52:57';
select left(#S, 2) + substring(#S, 4, 2)/60.0 + right(#S, 2)/60.0/60.0;
If you not always have two digit values you can use parsename to get the values instead.
declare #S varchar(20) = '088:052:057';
select parsename(S.X, 3) + parsename(S.X, 2)/60.0 + parsename(S.X, 1)/60.0/60.0
from (select replace(#S, ':', '.')) as S(X)
Try it like this (best create an UDF from this):
First I split the Time-Variable on its double dots via XML. The rest is simple calculation...
DECLARE #YourTime VARCHAR(100)='88:52:57';
WITH Splitted AS
(
SELECT CAST('<x>' + REPLACE(#YourTime,':','</x><x>') + '</x>' AS XML) TimeParts
)
,TimeFract AS
(
SELECT TimeParts.value('/x[1]','float') AS HourPart
,CAST(TimeParts.value('/x[2]','int') * 60 + TimeParts.value('/x[3]','int') AS FLOAT) Seconds
FROM Splitted
)
SELECT HourPart + Seconds/3600
FROM TimeFract
The result
88,8825
Try this, solution is based on conversions, making it safe, if the format is always (h)h:mi:ss:
DECLARE #S varchar(8) = '88:52:57';
SELECT
CAST(REPLACE(left(#S, 2), ':', '') as int)+
CAST(CAST(CAST('0:'+RIGHT(#S, 5) as datetime) as decimal(10,10)) * 24 as decimal(2,2))
Result:
88.88

Get everything after and before certain character in SQL Server

I got the following entry in my database:
images/test.jpg
I want to trim the entry so I get: test
So basically, I want everything after / and before .
How can I solve it?
use the following function
left(#test, charindex('/', #test) - 1)
If you want to get this out of your table using SQL, take a look at the following functions that will help you: SUBSTRING and CHARINDEX. You can use those to trim your entries.
A possible query will look like this (where col is the name of the column that contains your image directories:
SELECT SUBSTRING(col, LEN(SUBSTRING(col, 0, LEN(col) - CHARINDEX ('/', col))) + 1,
LEN(col) - LEN(SUBSTRING(col, 0, LEN(col) - CHARINDEX ('/', col))) - LEN(SUBSTRING(
col, CHARINDEX ('.', col), LEN(col))));
Bit of an ugly beast. It also depends on the standard format of 'dir/name.ext'.
Edit:
This one (inspired by praveen) is more generic and deals with extensions of different length:
SELECT SUBSTRING(col, LEN(LEFT(col, CHARINDEX ('/', col))) + 1, LEN(col) - LEN(LEFT(col,
CHARINDEX ('/', col))) - LEN(RIGHT(col, LEN(col) - CHARINDEX ('.', col))) - 1);
Before
SELECT SUBSTRING(ParentBGBU,0,CHARINDEX('/',ParentBGBU,0)) FROM dbo.tblHCMMaster;
After
SELECT SUBSTRING(ParentBGBU,CHARINDEX('-',ParentBGBU)+1,LEN(ParentBGBU)) FROM dbo.tblHCMMaster
----select characters before / including /
select SUBSTRING ('abcde/wxyz',0,CHARINDEX('/','abcde/wxyz')+1)
--select characters after / including /
select SUBSTRING('abcde/wxyz',CHARINDEX('/','abcde/wxyz'),LEN('abcde/wxyz'))
declare #T table
(
Col varchar(20)
)
insert into #T
Select 'images/test1.jpg'
union all
Select 'images/test2.png'
union all
Select 'images/test3.jpg'
union all
Select 'images/test4.jpeg'
union all
Select 'images/test5.jpeg'
Select substring( LEFT(Col,charindex('.',Col)-1),charindex('/',Col)+1,len(LEFT(Col,charindex('.',Col)-1))-1 )
from #T
I have made a method which is much more general :
so :
DECLARE #a NVARCHAR(MAX)='images/test.jpg';
--Touch here
DECLARE #keysValueToSearch NVARCHAR(4000) = '/'
DECLARE #untilThisCharAppears NVARCHAR(4000) = '.'
DECLARE #keysValueToSearchPattern NVARCHAR(4000) = '%' + #keysValueToSearch + '%'
--Nothing to touch here
SELECT SUBSTRING(
#a,
PATINDEX(#keysValueToSearchPattern, #a) + LEN(#keysValueToSearch),
CHARINDEX(
#untilThisCharAppears,
#a,
PATINDEX(#keysValueToSearchPattern, #a) + LEN(#keysValueToSearch)
) -(PATINDEX(#keysValueToSearchPattern, #a) + LEN(#keysValueToSearch))
)
SELECT Substring('ravi1234#gmail.com', 1, ( Charindex('#', 'ravi1234#gmail.com')
- 1 ))
Before,
RIGHT('ravi123#gmail.com', ( Charindex('#', 'ravi123#gmail.com') + 1 ))
After
I just did this in one of my reports and it was very simple.
Try this:
=MID(Fields!.Value,8,4)
Note: This worked for me because the value I was trying to get was a constant not sure it what you are trying to get is a constant as well.
I know this has been a while.. but here is an idea
declare #test varchar(25) = 'images/test.jpg'
select
#test as column_name
, parsename(replace(#test,'/','.'),1) as jpg
,parsename(replace(#test,'/','.'),2) as test
,parsename(replace(#test,'/','.'),3) as images
I found Royi Namir's answer useful but expanded upon it to create it as a function. I renamed the variables to what made sense to me but you can translate them back easily enough, if desired.
Also, the code in Royi's answer already handled the case where the character being searched from does not exist (it starts from the beginning of the string), but I wanted to also handle cases where the character that is being searched to does not exist.
In that case it acts in a similar manner by starting from the searched from character and returning the rest of the characters to the end of the string.
CREATE FUNCTION [dbo].[getValueBetweenTwoStrings](#inputString
NVARCHAR(4000), #stringToSearchFrom NVARCHAR(4000), #stringToSearchTo
NVARCHAR(4000))
RETURNS NVARCHAR(4000)
AS
BEGIN
DECLARE #retVal NVARCHAR(4000)
DECLARE #stringToSearchFromSearchPattern NVARCHAR(4000) = '%' +
#stringToSearchFrom + '%'
SELECT #retVal = SUBSTRING (
#inputString,
PATINDEX(#stringToSearchFromSearchPattern, #inputString) + LEN(#stringToSearchFrom),
(CASE
CHARINDEX(
#stringToSearchTo,
#inputString,
PATINDEX(#stringToSearchFromSearchPattern, #inputString) + LEN(#stringToSearchFrom))
WHEN
0
THEN
LEN(#inputString) + 1
ELSE
CHARINDEX(
#stringToSearchTo,
#inputString,
PATINDEX(#stringToSearchFromSearchPattern, #inputString) + LEN(#stringToSearchFrom))
END) - (PATINDEX(#stringToSearchFromSearchPattern, #inputString) + LEN(#stringToSearchFrom))
)
RETURN #retVal
END
Usage:
SELECT dbo.getValueBetweenTwoStrings('images/test.jpg','/','.') AS MyResult
I got some invalid length errors. So i made this function, this should not give any length problems. Also when you do not find the searched text it will return a NULL.
CREATE FUNCTION [FN].[SearchTextGetBetweenStartAndStop](#string varchar(max),#SearchStringToStart varchar(max),#SearchStringToStop varchar(max))
RETURNS varchar(max)
BEGIN
SET #string = CASE
WHEN CHARINDEX(#SearchStringToStart,#string) = 0
OR CHARINDEX(#SearchStringToStop,RIGHT(#string,LEN(#string) - CHARINDEX(#SearchStringToStart,#string) + 1 - LEN(#SearchStringToStart))) = 0
THEN NULL
ELSE SUBSTRING(#string
,CHARINDEX(#SearchStringToStart,#string) + LEN(#SearchStringToStart) + 1
,(CHARINDEX(#SearchStringToStop,RIGHT(#string,LEN(#string) - CHARINDEX(#SearchStringToStart,#string) + 1 - LEN(#SearchStringToStart)))-2)
)
END
RETURN #string
END
if Input= pg102a-wlc01s.png.intel.com and Output should be pg102a-wlc01s
we can use below query :
select Substring(pc.name,0,charindex('.',pc.name,0)),pc.name from tbl_name pc
You can try this:
Declare #test varchar(100)='images/test.jpg'
Select REPLACE(RIGHT(#test,charindex('/',reverse(#test))-1),'.jpg','')
Below query gives you data before '-'
Ex- W12345A-4S
SELECT SUBSTRING(Column_Name,0, CHARINDEX('-',Column_Name)) as 'new_name'
from [abc].
Output - W12345A
Inspired by the work of Josien, I wondered about a simplification.
Would this also work? Much shorter:
SELECT SUBSTRING(col, CHARINDEX ('/', col) + 1, CHARINDEX ('.', col) - CHARINDEX ('/', col) - 1);
(I can't test right now because of right issues at my company SQL server, which is a problem in its own right)
Simply Try With LEFT ,RIGHT ,CHARINDEX
select
LEFT((RIGHT(a.name,((CHARINDEX('/', name))+1))),((CHARINDEX('.', (RIGHT(a.name,
((CHARINDEX('/', name))+1)))))-1)) splitstring,
a.name
from
(select 'images/test.jpg' as name)a
declare #searchStart nvarchar(100) = 'search ';
declare #searchEnd nvarchar(100) = ' ';
declare #string nvarchar(4000) = 'This is a string to search (hello) in this text ';
declare #startIndex int = CHARINDEX(#searchStart, #string,0) + LEN(#searchStart);
declare #endIndex int = CHARINDEX(#searchEnd, #string, #startIndex + 1);
declare #length int = #endIndex - #startIndex;
declare #sub nvarchar(4000) = SUBSTRING(#string, #startIndex, #length)
select #startIndex, #endIndex, #length, #sub
This is a little more legible than the one-liners in this answer which specifically answer the question, but not in a generic way that would benefit all readers. This could easily be made into a function as well with a slight modification.
If there are more than one or none occurences of given character use this:
DECLARE #rightidx int = CASE
WHEN 'images/images/test.jpg' IS NULL OR (CHARINDEX('.', 'images/images/test.jpg')) <= 0 THEN LEN('images/images/test.jpg')
ELSE (CHARINDEX('.', REVERSE('images/images/test.jpg')) - 1)
END
SELECT RIGHT('images/images/test.jpg', #rightidx)
This was the approach I took.
CREATE FUNCTION dbo.get_text_before_char(#my_string nvarchar(255),#my_char char(1))
RETURNS nvarchar(255)
AS
BEGIN;
return IIF(#my_string LIKE '%' + #my_char + '%',left (#my_string, IIF(charindex(#my_char, #my_string) - 1<1,1,charindex(#my_char, #my_string) - 1)),'');
END;
CREATE FUNCTION dbo.get_text_after_char(#my_string nvarchar(255),#my_char char(1))
RETURNS nvarchar(255)
AS
BEGIN;
return IIF ( #my_string LIKE '%' + #my_char + '%' ,RIGHT ( #my_string , IIF ( charindex ( #my_char ,reverse(#my_string) )-1 < 1 ,1 ,charindex ( #my_char ,reverse(#my_string) )-1 ) ) , '' )
END;
SELECT
dbo.get_text_before_char('foo-bar','-')
, dbo.get_text_after_char('foo-bar','-')
declare #test varchar(100)='images/test.jpg'
select right(left(#test, charindex('.', #test) - 1),4)

How to display the number “12” in the format of “0000012”

How to display the number “12” in the format of “0000012” Using SQL
if you just want the number 12 then
SELECT '0000012'
else if it is a number you need to display with 7 digits:
SELECT RIGHT('0000000'+CONVERT(nvarchar,FieldValue),7)
More info on the question would help.
How about something like
DECLARE #Val INT
DECLARE #Length INT
SELECT #Val = 12,
#Length = 7
SELECT REPLICATE('0',#Length - LEN(CAST(#Val AS VARCHAR(MAX)))) + CAST(#Val AS VARCHAR(MAX))
REPLICATE (Transact-SQL)
Repeats a string value a specified
number of times.
The shortest answer that probably also works best is just
SELECT RIGHT(10000000+ #Val, #Length)
e.g.
SELECT RIGHT(10000000+ NumColumn, 7)
I haven't got a server to test with, but you should be able to use the following in your SQL:
'RN ' + RIGHT(CAST(auto_id AS VarChar) + '000000', 6)
eg:
Code:
SELECT 'RN ' + RIGHT(CAST(auto_id AS VarChar) + '000000', 6)
FROM tablename
This is not efficient but will work for your case -
DECLARE #num int
DECLARE #totalChar int
SET #num = 12
SET #totalChar = 10
SELECT right('0000000000' + CONVERT(varchar, #num), #totalChar)
Output -
000000012
This should easily port to other SQLs:
SELECT
REVERSE(CAST(REVERSE(CAST(CAST(12 AS INTEGER) AS VARCHAR(7))) + '000000' AS CHAR(7)))
SELECT REPLACE(STR(12, 7), ' ', '0')

Convert NVARCHAR to money value

I'm trying to convert an NVARCHAR value to a money value with MsSQL.
I know I can use something like:
SELECT CONVERT(money, ValueColumn) FROM SomeTable
But the problem is when I have a value 4352,50, and I call the convert method, the value becomes 435250,00
What am I missing? I also tried CONVERT(money, ValueColumn, 2) but without any success.
Thanks in advance!
SELECT CONVERT(money, REPLACE('4352,50', ',', '.'))
As you are working in ,- as-decimal-separator use this:
SELECT CONVERT(money, REPLACE(ValueColumn, ',', '.'))
Try
DECLARE #ValueColumn NVARCHAR(20)
SELECT #ValueColumn = '4352.50'
SELECT CONVERT(money, #ValueColumn)
VS
DECLARE #ValueColumn NVARCHAR(20)
SELECT #ValueColumn = '4352,50'
SELECT CONVERT(money, #ValueColumn)
The comma is not being intepreted as the decimal point.
This is a bit of a hack but if the rest of your data is the same format
e.g
numbers , numbers ,
Declare #Value nvarchar(50)
Set #Value = '4352,50,'
Select Convert(Money, Substring(#Value, 0, Charindex(',',#value)) + '.' + Substring(#Value, Charindex(',',#Value)+1, 2))
SELECT TRY_PARSE('12.345,67' AS Money USING 'pt-BR')