T-SQL function to convert int to varchar with plus/minus sign - sql-server

While I've been troubled by annoying SQL operations, I've got another T-SQL problem.
I have to convert some Int variables into zero-filled varchar with plus/minus sign.
I have tried RIGHT() and CONVERT() functions so far,
RIGHT('000000' + CONVERT(value1 AS VARCHAR(6)), 6)
but I couldn't figure out what the best way to convert them.
What I would like to see is:
If value1 = 305 then '+000305'
If value1 = -110 then '-000110'
Is there any simple function to achieve this? Or should I have to create my own function for this?
I know it's stupid question, but my current task requires a lot of such non-sense tasks to Stored Procedures (database-side) rather than 'application-side'.
Thanks.

You want to use CAST instead of CONVERT when you structure it that way. There's no standard function that will do what you want, but you could create an expression like this to get what you need:
LEFT(REPLACE(SIGN(value1),'1','+'),1) + RIGHT('000000' + CAST(ABS(value1) AS VARCHAR(6)), 6)
If you want to use CONVERT it would look like:
LEFT(REPLACE(SIGN(value1),'1','+'),1) + RIGHT('000000' + CONVERT(VARCHAR(6),ABS(value1)), 6)
Just for fun, here's another way you could do it:
LEFT(REPLACE(SIGN(value1),'1','+'),1) + REPLACE(STR(ABS(value1),5),' ','0')

For SQL 2012 and above, you can use FORMAT().
DECLARE #yourTable TABLE (nums INT);
INSERT INTO #yourTable VALUES (305),(-110);
SELECT RIGHT('+' + FORMAT(nums,'00000#'),7) AS formatted_nums
FROM #yourTable
Results:
formatted_nums
--------------
+000305
-000110

may be this one can achieved in both ways using REPLACE or Replicate function.
DECLARE #t TABLE (Num INT)
INSERT #t
SELECT 305
UNION SELECT -110
SELECT CASE WHEN Num < 0 THEN '-' ELSE '+' END +
replace(RIGHT('00000'+ CONVERT(VARCHAR,Num),8),'-','0') AS NUM
FROM #t
SELECT CASE WHEN Num < 0 THEN '-' ELSE '+' END +
RIGHT(Replicate('0',6) + CONVERT(VARCHAR,Abs(Num)), 6)
FROM #t

Related

T-SQL Right Function default value

I am working towards migrating an access Right() function onto SQL Server.
This is the Access Right() function:
Barcode: "ID" & (Right(String(8,"0") & [Job Number],8) & Right(String(6,"0") &
[PART LIBARY HEADER_1]![PartID],6) & Right(String(6,"0") & [Part Assembly Link
Table]![AssemblyLinkID],6))
What the above expression does, is that it dynamically creates a field to house a barcode that is always 22 characters in length. Now the values of these barcodes are determined by other columns.
I am using the Right() method to gather the Rightmost: 8 chars of Job Number, 6 chars of PartID and 6 chars of AssemblyLinkID.
Now the problem I face is that whilst I can move these values onto T-SQL, I having difficulty setting the default value to be = 0.
For example the following input:
Job Number: 123456
PartID: 9876
AssemblyLinkID: 127
Would need to return… ID00123456009876000127
The String() function in access is handling the null values for me by appending with 0 but this method is not something available in SQL Server.
String(8,"0")
This is my SQL Code so far:
Concat('ID', RIGHT(STR(0, 8) & [Job Number],8)) AS Barcode,
STR() is not the function I am looking to use as it is not giving the same results as MS Access's String().
This does the job you want:
declare #t table ([Job NUmber] int, PartID int, AssemblyLinkID int)
insert into #t ([Job NUmber], PartID, AssemblyLinkID) values(123456,9876,127)
select
'ID' +
RIGHT('00000000' + CONVERT(varchar(8),[Job Number]),8) +
RIGHT('000000' + CONVERT(varchar(6),PartID),6) +
RIGHT('000000' + CONVERT(varchar(6),AssemblyLinkID),6)
from #t
You can use REPLICATE as an exact analogue for your STRING calls but since the string literals are shorter than the method call, I prefer them.
Not sure quite what your point was around nulls, but if any of these columns may be NULL, then you may way to use COALESCE as well:
declare #t table ([Job NUmber] int, PartID int, AssemblyLinkID int)
insert into #t ([Job NUmber], PartID, AssemblyLinkID) values(123456,9876,127)
select
'ID' +
RIGHT('00000000' + COALESCE(CONVERT(varchar(8),[Job Number]),''),8) +
RIGHT('000000' + COALESCE(CONVERT(varchar(6),PartID),''),6) +
RIGHT('000000' + COALESCE(CONVERT(varchar(6),AssemblyLinkID),''),6)
from #t
(Here we'll get all zeros for a NULL value. If you want something different, substitute that into the empty string towards the end of each expression)
Right(String(8,"0") & [Job Number],8) =
RIGHT(REPLICATE('0', 8) + ISNULL([Job Number], ''), 8)

How to add zero in front of numeric value in T-SQL 2005 or 2008?

I have to export a table in fixed format way. When I have numeric field, I have to add leading zeroes.
I know with SQL Server 2012, I can use FORMAT(). How to do in SQL Server 2005?
For instance, in a column with number 18, with fixed length 10, I have to export:
0000000018
You have to convert it to a varchar and use right.
select right(replicate('0', 10) + convert(varchar(10), YourNumberColumn), 10)
I prefer the syntax
SELECT REPLACE(STR(YourNumber,X),' ','0')
The X is the count of digits you want.
The advantage: Other approaches would cut the number and lead to wrong results, if the input is wider than the target length. This approach would create a chain of asterisc ("***")
Try this
DECLARE #tbl TABLE(Nmbr INT)
INSERT INTO #tbl VALUES(1),(12),(123),(1234);
SELECT REPLACE(STR(Nmbr,3),' ','0')
FROM #tbl
The result:
001
012
123
***
right('00000000' + cast(YourValue as varchar(10)), 10)
You can make like this
replicate('0', 10 - Floor(LOG10(myField) + 1) + myField

SQL Server : Replace (Charindex)

I have a SQL Server table with numbers in column no:
12345670000115
14245670000116
58492010000118
I need a function that will remove one number 1 from right side of number, so result must be like:
1234567000015
1424567000016
5849201000018
I find some solutions to use charindex() with substring(), but my SQL skills are poor so I really need help.
Thanks
Assuming this is varchar data here is an easy way to accomplish this. BTW, I would suggest you not use column names like 'no'. It is a reserved word and it is horribly ambiguous. Does that mean number or the opposite of yes? If it is number as I assume it would be better to name the column with an indication of what the number is. PartNumber, ItemNumber, CatalogNumber whatever...
LEFT(no, len(no) - 2) + RIGHT(no, 1)
Try to use this query:
declare #charToReplace char = '1'
select REVERSE(stuff(REVERSE(no), charindex(#charToReplace, REVERSE(no)), 1, ''))
from table
or
declare #charToReplace char = '1'
declare #tmp_table TABLE (NO varchar(16))
insert into #tmp_table
select REVERSE(NO)
from yourtable
select REVERSE(stuff(NO, charindex(#charToReplace, NO), 1, ''))
For your particular data, if the numbers fit a BIGINT, one easy way is to treat them like numbers:
Setup
create table #tmp (
number VARCHAR(16)
)
insert into #tmp values ('12345670000115'), ('14245670000116'), ('58492010000118')
GO
Script:
select number, cast( (cast(number AS bigint) - 100) / 100 * 10 + cast(number AS bigint) % 100 as VARCHAR(16))
from #tmp
GO
I resolve problem. There is answer in which I remove one character 1 and update whole table. Thanks all for help!
Update myTableName
set barcode=substring(barcode,1,11)+substring(barcode,13,1)
where len(barcode)>= 14

Converting nvarchar to numeric

I have variable called #prmclientcode which is nvarchar. The input to this variable can be a single client code or multiple client codes separated by comma. For e.g.
#prmclientcode='1'
or
#prmclientcode='1,2,3'.
I am comparing this variable to a client code column in of the tables. The data type of this column is numeric(6,0). I tried converting the variable data type like below
SNCA_CLIENT_CODE IN ('''+convert(numeric(6,0),#prmclientcode+''')) (The query is inside a dynamic sql).
But when I try executing this I get the error
Arithmetic overflow error converting nvarchar to data type numeric.
Can anyone please help me here!
Thanks!
You need to convert the numeric(6,0) column to nvarchar data type. You can use below scrip to convert it to nvarchar, before processing:
SNCA_CLIENT_CODE IN ('''+convert(cast( numeric(6,0) as nvarchar(max) ),#prmclientcode+'''))
Please try with the below code snippet.
DECLARE #ProductTotals TABLE
(
ProductID int
)
INSERT INTO #ProductTotals VALUES(1)
INSERT INTO #ProductTotals VALUES(11)
INSERT INTO #ProductTotals VALUES(3)
DECLARE #prmclientcode VARCHAR(MAX)='1'
SELECT * FROM #ProductTotals
SELECT * FROM #ProductTotals WHERE CHARINDEX(',' + CAST(ProductID AS VARCHAR(MAX)) + ',' , ',' + ISNULL(#prmclientcode,ProductID) + ',') > 0
Let me know if any concern.
use following code in order to separate your variable:
DECLARE
#T VARCHAR(100) = '1,2,3,23,342',
#I int = 1
;WITH x(I, num) AS (
SELECT 1, CHARINDEX(',',#T,#I)
UNION ALL
SELECT num+1,CHARINDEX(',',#T,num+1)
FROM x
WHERE num+1<LEN(#T)
AND num<>0
)
SELECT SUBSTRING(#T,I,CASE WHEN num=0 THEN LEN(#T)+1 ELSE num END -I)
FROM x
Use can use either table function or dynamic sql query, both options will work.
Let me know if you need more help

How to add or concatenate money type and string on query mssql

I have a situation like this
I got a column with 'money' type, 2 decimal . Example data:(65.00)
I need to add 12 zero / 000000000000 to it so that the output would be like this:
(65.00 convert to 6500) + (000000000000) = 000000006500
Output: 000000006500
How can I achieve this?. Thank you for your help and suggestion
You can do this with a couple of casts, multiplying by 100, and using REPLICATE('0') to pad with the requisite number of zeroes).
I'm assuming you DO want up to 2 x trailing decimals, but no more.
DECLARE #value MONEY;
SET #value = 65.123;
DECLARE #intValue BIGINT;
SET #intValue = CAST(#value * 100.0 AS BIGINT);
SELECT REPLICATE('0',12-LEN(#intValue)) + CAST(#intValue AS NVARCHAR(20));
Returns 000000006512
If you need to do this on a set, a CTE can be used for the intermediate step, e.g.
WITH cte AS
(
SELECT CAST(MoneyField * 100.0 AS BIGINT) AS intValue
FROM SomeTable
)
SELECT
REPLICATE('0',12-LEN(cte.intValue)) + CAST(cte.intValue AS NVARCHAR(20))
FROM cte;
Fiddle here
It is Possible .But output Column should be in the type of varchar(15) .If you want to do further operation of your output you have to convert that into int or whatever
SELECT CONCAT(REPEAT('0',12-LENGTH(65.00)),(65.00*100));

Resources