sql convert text string from 1 integer (8) to 3 integers (888) - sql

I am having a little difficulty with the below code - it return the value I am after, but I need the value 3 digits long - i.e. it returns '1' but I need '001' - any help would be gratefully received
select convert(varchar(3),(select count(ptMatter) + 1 from lamatter where
convert(varchar(10), getdate(), 103)=convert(varchar(10), dateadd, 103)))

Select Right('000000' + convert(varchar(3), Result),3)
From yourTable
for your exact query:
Select Right('000000' + convert(varchar(3), (select count(ptMatter) + 1 from lamatter where convert(varchar(10), getdate(), 103)=convert(varchar(10), dateadd, 103)) ),3)

Look at your database documentation if the lpad function exists. For example, this is the mysql version : http://dev.mysql.com/doc/refman/5.1/en/string-functions.html#function_lpad
edit: sorry, didn't saw the tsql tag... Like said in another answer, the right function is the way to go, like explained here : Most efficient T-SQL way to pad a varchar on the left to a certain length?

What about something like this:
DECLARE #i int;
SELECT #i = 1;
SELECT REPLACE(STR(#i, 3), ' ', '0')

Related

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

How to format numeric value when casting to varchar?

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

Formatting a number as a monetary value including separators

I need some help with a sql transformation. This part of query that I have been provided with:
'$' + replace(cast((CAST(p.Price1 AS decimal(10,2)) * cast(isnull(p.Multiplier,1) as decimal(10,2))) as varchar), '.0000', '')
Basically, it ends up being a varchar that looks like this: $26980
I need to insert a comma at the thousand and million mark (if applicable). So in this instance, $26,980
What's the easiest way to do that without having to rewrite the whole thing?
Do it on the client side. Having said that, this example should show you the way.
with p(price1, multiplier) as (select 1234.5, 10)
select '$' + replace(cast((CAST(p.Price1 AS decimal(10,2)) * cast(isnull(p.Multiplier,1) as decimal(10,2))) as varchar), '.0000', ''),
'$' + parsename(convert(varchar,cast(p.price1*isnull(p.Multiplier,1) as money),1),2)
from p
The key is in the last expression
'$' + parsename(convert(varchar,cast(p.price1*isnull(p.Multiplier,1) as money),1),2)
Note: if p.price1 is of a higher precision than decimal(10,2), then you may have to cast it in the expression as well to produce a faithful translation since the original CAST(p.Priced1 as decimal(10,2)) will be performing rounding.
If you really must do it in TSQL you can use CONVERT(), but this sort of thing really doesn't belong in the database:
declare #m money = 12345678
-- with decimal places
select '$' + convert(varchar, #m, 1)
-- without decimal places
select '$' + replace(convert(varchar, #m, 1), '.00', '')
You could turn this into a function, it only goes 50 characters back.
DECLARE #input VARCHAR(50)
SELECT #input = '123123123.00'
SELECT #input = CASE WHEN CHARINDEX('.', #input) > offset +1
THEN STUFF(#input, CHARINDEX('.', #input) - offset, 0, ',')
ELSE #input END
FROM (SELECT 3 offset UNION SELECT 7 UNION SELECT 12 UNION SELECT 18 UNION SELECT 25 UNION SELECT 33 UNION SELECT 42) b
PRINT #input
The offset grows by +1 for each position, because it's assuming you've already inserted the commas for the previous positions.

Sql concatenate problem?

In my table i have a column called Dep_user_code which is nothing but employeeid...Everytime I need to increment the employeeid when i insert a new value..but it has both alphabet and number..i need to increment the number alone.. for example if my employeeid is 'NECUSER0001' means next time when i insert a new employeeid it has to be 'NECUSER0002' dynamically i have to generate like this..everytime when i insert a value it has to increment..
I have tried like taking the string part and number part like this but dont know how to implement this...Any suggestion?
select SUBSTRING(Dep_user_code,1,7) from NEC_Customer_User_Map
select SUBSTRING(Dep_user_code,8,4) from NEC_Customer_User_Map
you should also keep an identity key. use SELECT IDENT_CURRENT('NEC_Customer_User_Map') to find out last inserted ID.
If the value is always text then numbers, you split apart the value using Patindex:
Select Substring( Dep_user_code, 1, PatIndex( '%[0-9]%', Dep_user_code) - 1 ) As TextPortion
, Substring( Dep_user_code, PatIndex( '%[0-9]%', Dep_user_code)
, Len(Dep_user_code) ) As NumberPortion
However, whether you can use an identity in combination with a prefix depends on whether you can allow gaps. If you cannot allow gaps, then you need to query for the next id value that you can use which can be done in a variety of ways depending on the needs.
I've had to support databases with setups like this before and while I'm generally not a fan of this style, I'm assuming you have some reason for not storing the NECUSER in one column and the incrementing identity integer in another column with the PK set to both. If not, I'd suggest going that route and letting SQL do the work for you.
Otherwise, using the result of the following query should yield the results you want. I've added comments to try and answer any questions the query might raise.
SELECT SUBSTRING(Dep_user_code, 1, 7) +
RIGHT(
REPLICATE('0', 3) + --Ensure we have padding 0s
IsNull(MAX(CAST(SUBSTRING(Dep_user_code, 8, 4) AS INT), -1) + 1 --Work with ints, find MAX or set NULL to -1 so +1 will = 0
, 4) --Only want 4 character total from RIGHT function
FROM NEC_Customer_User_Map
WITH last AS (
SELECT MAX(Dep_user_code) AS Code
FROM NEC_Customer_User_Map
WHERE LEFT(Dep_user_code, 7) = 'NECUSER'
)
SELECT LEFT(Dep_user_code, 7) + RIGHT(CAST(STUFF(Code, 1, 7, '1') AS int) + 1, 4)
FROM last
The RIGHT part does the following:
replaces 'NECUSER' with '1' thus getting something like '10002';
casts the result as int;
increments by 1;
(implicitly) casts the value to varchar and gets the last 4 chars.
Maybe STUFF(Code, 1, 7, '1') should better be replaced with '1' + RIGHT(Code, 4), not sure.
EDIT: As it happens, the implicit conversion could also be employed in case of converting the string to the integer too:
... + RIGHT(STUFF(Code, 1, 7, '1') + 1, 4) ...
or
... + RIGHT('1' + RIGHT(Code, 4) + 1, 4) ...
declare #max varchar(20)
declare #number varchar(20)
select #max = max(cast(substring(dep_user_name , 8, 4) as int)) from NEC_Customer_User_Map (nolock)
select #max = isnull(#max, 0) + 1
select #max = (case when len(#max) = 1 then '000' + #max
when len(#max) = 2 then '00' + #max
when len(#max) = 3 then '0' + #max
else #max
end)
Select #number = (Substring( dep_user_name, 1, PatIndex( '%[0-9]%', dep_user_name) - 1 ) + #max) from NEC_Customer_User_Map
insert into NEC_Customer_User_Map(Dep_User_Name) values (#number )
You can consider to have both parts of Dep_user_code as separate fileds in your db in order to take advantage of several tsql features like IDENTITY and IDENT_CURRENT()

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')