In SQL Server 2000 how do you add 0's to beginning of number to fill nchar(n) - sql-server-2000

I'm trying to add 0's to the beginning of an nchar(n). Is their a format function in SQL Server 2000 to add 0's to an int so that it will always have n number of digits with leading 0's:
example
int nchar(n)
1 0000..1
2 0000002
3 0000003
...
10 0000010
11 0000011
...
100 0000100
...
1000 0001000

Sorry for being slightly off-topic, but are you really sure that this is a problem that should be dealt with on a database level rather than in presentation level? I mean, database can and should store those numbers as-is, and only in presentation code do you add all the leading zeroes.

e.g. for n=12
DECLARE #foo bigint
DECLARE #bar bigint
SET #foo=12345678901
SET #bar=12
SELECT RIGHT('000000000000' + CAST(#foo AS VARCHAR(12)),12)
SELECT RIGHT('000000000000' + CAST(#bar AS VARCHAR(12)),12)
Beware! This won't work for numbers with more than n digits!

Related

Reverse characters in string with mixed Left-to-right and Right-to-left languages using SQL 2?

I have string values in my table which includes Hebrew characters (or any R-T-L language for this case) and English ones (or numbers).
The problem is that the English characters are reversed and looks like: בדיקה 123456 esrever sti fI kcehC.
The numbers and the English characters are reversed, the Hebrew ones are fine.
How can I use built in SQL functions to identify the English substring (and the numbers) and reverse it while maintain the order on the other RTL characters?
I read an answer to this problem in the following link:
Reverse characters in string with mixed Left-to-right and Right-to-left languages using SQL?
The solution:
DECLARE #sourceString NVARCHAR(100) = N'123456 בדיקה esrever sti fI kcehC';
DECLARE #reversedString NVARCHAR(4000) = nchar(8237) + REVERSE(#sourceString) + nchar(8236)
SELECT #reversedString;
My problem:
When I try to build queries with this option it does not work For example:
select count(*) from table where nchar(8237) + REVERSE(column) + nchar(8236) = N'‭Check If its reverse הקידב 654321‬'
How can I fix it?
The behavior of RTL strings in SQL-Server, especially when mixed, is sometimes really odd.
I don't know exactly what you are trying to achieve, but this would - at least - give you the unicode code points:
DECLARE #source NVARCHAR(100)=N'123456 בדיקה esrever sti fI kcehC';
WITH cte AS
(
SELECT 1 AS pos
,UNICODE(SUBSTRING(#source,1,1)) AS CodeAtPosition
UNION ALL
SELECT cte.pos+1
,UNICODE(SUBSTRING(#source,cte.pos+1,1))
FROM cte
WHERE pos<LEN(#source)
)
SELECT *
FROM cte
The hebrew characters are from a much higher range:
pos CodeAtPosition
1 49
2 50
3 51
4 52
5 53
6 54
7 32
8 1489 <-- starting here
9 1491
10 1497
11 1511
12 1492 <-- ending here
13 32
14 101
...more rows
Helpful answer: https://stackoverflow.com/a/29821207/5089204
Something about bidi-text: https://www.w3.org/TR/WCAG20-TECHS/H34.html

How to count string between string in sql

I have a data that having different length of value.
For example I have 2 rows of data:
CL-CI/PST/102/VII/2016
CL-CI/PST/0102/VII/2016
The difference between them is 102 (3 digits) and 0102 (4 digits)
I want in my SQL checking:
if (3Digits)
begin
....
end
else
begin
....
end
The records of data format is not fixed. Just not fixed on this string VII/2016 (based on month in roman numerals/year).
I know how to count the string is using LEN. But my problem is when I select top 1 of data. In this top 1 data that I got, I want to check dynamically if it is 4 digits / 3 digits that I got from that top 1. I'm stuck on this.
Try it like this
Easy: Just the length
DECLARE #s VARCHAR(100)='CL-CI/PST/0102/VII/2016';
SELECT LEN(CAST('<x>' + REPLACE(#s,'/','</x><x>')+'</x>' AS XML).value('/x[3]','varchar(max)'))
The result is 4
setbased approach
DECLARE #tbl TABLE(ID INT IDENTITY,YourString VARCHAR(100),OtherValue VARCHAR(100));
INSERT INTO #tbl(YourString,OtherValue) VALUES
('CL-CI/PST/102/VII/2016','With 3 digits')
,('CL-CI/PST/0102/VII/2016','With 4 digits');
WITH ExtendByPart3 AS
(
SELECT *
,CAST('<x>' + REPLACE(YourString,'/','</x><x>')+'</x>' AS XML).value('/x[3]','varchar(max)') AS Part3
FROM #tbl
)
SELECT *,LEN(Part3) AS LenPart3 FROM ExtendByPart3
The result
ID YourString OtherValue Part3 LenPart3
1 CL-CI/PST/102/VII/2016 With 3 digits 102 3
2 CL-CI/PST/0102/VII/2016 With 4 digits 0102 4
Btw: There are several questions about: How to access item X of a seperated string and most answers come with very complex CTEs, loops, CLR methods... This approach is direct and type safe. Change the nvarchar(max) of the .value() function to int and you would get the number - if needed.
I placed an answer to one of these questions myself, but - as this question is existing for years - the leading answers are very old fashioned and - IMO - outdated. But still it migth be worth reading this...
Retrieve all values
If you might be interested in your other values too, you could do this:
DECLARE #tbl TABLE(ID INT IDENTITY,YourString VARCHAR(100),OtherValue VARCHAR(100));
INSERT INTO #tbl(YourString,OtherValue) VALUES
('CL-CI/PST/102/VII/2016','With 3 digits')
,('CL-CI/PST/0102/VII/2016','With 4 digits');
WITH Splitted AS
(
SELECT CAST('<x>' + REPLACE(YourString,'/','</x><x>')+'</x>' AS XML) AS XMLData
FROM #tbl
)
SELECT XMLData.value('/x[1]','varchar(max)') AS Part1
,XMLData.value('/x[2]','varchar(max)') AS Part2
,XMLData.value('/x[3]','int') AS Number
,XMLData.value('/x[4]','varchar(max)') AS MonthRoman
,XMLData.value('/x[5]','int') AS TheYear
FROM Splitted
The result (attention: as returned as int the Number is without the leading zero)
Part1 Part2 Number MonthRoman TheYear
CL-CI PST 102 VII 2016
CL-CI PST 102 VII 2016
Perhaps case and like are sufficient:
select (case when col like '%/%/[0-9][0-9][0-9]/%' then <3 digit stuff>
when col like '%/%/[0-9][0-9][0-9][0-9]/%' then <4 digit stuff>
end)

truncate integer

I got a task to chop an integer by 1 digit.
For example, If the new limit is 3 digits then 1234 will become 999 after the change. if the before change value is 12345 then it should becomes 999 after changes. if the pre-change value is 564 then it will remain unchanged.
This has to be done on Oracle as well as SQL server. the truc function only truncates decimal but not integer.
What is the best way to do this in SQL, PL/SQL or T-SQL?
Thanks in advance.
This works for T-SQL. Converting it to other sql dialects should just be as simple as finding the similar methods
declare #numDigits INT = 3;
declare #maxNumber INT = POWER(10,#numDigits)-1 -- gets "999" when using 3 digits, 9999 when using 4 etc
DECLARE #input INT = 1234
DECLARE #output INT = IIF(#input>#maxNumber,#maxNumber,#input)
SELECT #output -- selects 999
Oracle does have the POWER function, but does not have the ternary/IIF function
You could use case statements for this like:
SELECT CASE [yourInt] >= 1000 THEN 999 ELSE [yourInt] END AS 'UpperLimit'
From [YouTable]

SQL Server - Convert decimal to string with padding - implied decimal

I have a need to format numbers with padded zeros left and right. The number's precision is decimal (9,5). I am converting to a character string and need it to be a length of 4.
I am using SQL server 2008.
Here are some examples:
If 3.0 then I need 0003
If 30.0 then I need 0030
If 112.8 then I need 1128
If 120.0 then I need 1200
and so on.
I have tried multiple format functions like Right, Left, Replace, etc. But no combinations seem to get me the correct format.
Example below:
Right('00' + Replace(SUBSTRING(CAST(My_Table.My_Field as varchar),1,4),'.',''),4)
It works fine for the number 36.0 but this gets me 0212 for the number 212.0. I need it to be 2120
Another one
right('000'+replace(value,'.',''),4)
Maybe the following sql code will be useful:
SELECT
CASE WHEN NUMBER < 100
THEN RIGHT('0000' + CAST(CAST(NUMBER AS INT) AS VARCHAR),4)
ELSE RIGHT(SUBSTRING(CAST(NUMBER AS VARCHAR),1,CHARINDEX('.',CAST(NUMBER AS VARCHAR))-1),4) + LEFT(PARSENAME(NUMBER,1),1)
END RESULT
FROM TEST
You can try this here sqlfiddle.
Note: NUMBER is your field, and TEST is your TABLE.
If 3.0 is supposed to be 0030 and 30.0 is supposed to be 0300, which would make sense for if 120.0 is supposed to be 1200, then this select statement should work:
SELECT SUBSTR('0000'||REPLACE(TableName.NumberColumn,'.',''),-4,4) AS Output FROM TableName;
Try this one -
DECLARE #temp TABLE (Value DECIMAL(4,1))
INSERT INTO #temp (Value)
VALUES (3.0),(30.0), (112.8),(120.0)
SELECT RIGHT('000' + CAST(CAST(Value * 10 AS INT) AS VARCHAR(4)), 4)
FROM #temp
Output -
----
0030
0300
1128
1200

Pad a number with zeros, but only if it's below a certain length?

I have numbers that must be at least 7 digits long. For example:
0000001
123456789
0012345
Are all valid. I only need to pad the number with 0's only if its length is below 7. How do I do this in SQL Server? The best I've been able to get is to pad the number if the length is less than 7, but above that, it starts to truncate the number instead.
SELECT CASE WHEN LEN(CONVERT(VARCHAR(12), column)) > 7 THEN
CONVERT(VARCHAR(12),column) ELSE
RIGHT('0000000' + CONVERT(VARCHAR(12), column), 7) END
FROM dbo.table;
Aaron Bertrand beat me to it.
I'd like to add that it might also be useful to encapsulate both the character and number of times you have to repeat it, so that if it needs to change sometime in the future, it's easy to do it. You can do this using REPLICATE. So expanding on Aaron's example:
DECLARE #num_digits as int = 7
SELECT RIGHT(REPLICATE('0', #num_digits) + col, #num_digits) FROM dbo.table;
Hi check this out.
declare #num table(num varchar(10))
insert into #num
VALUES('0000001'),('123456789'),('0012345'),('123'),('11')
select CASE when len(num) < 7 then REPLICATE('0',(7-len(num)))+num else num END from #num