Select first 2 characters and replace others - sql-server

have dynamic numbers like this
33630521
4722829
36968
how can take first 2 numbers and replace others to 0 it can be varchar no problem
want result like this
33000000
4700000
36000
tried this
declare #first2 varchar(2) = (SELECT SUBSTRING('36968795', 1, 2))
declare #others varchar(100) = (SELECT SUBSTRING('36968795', 3, 100))
select #first2 + #others
but i stuck at replace #others to zeros because its unknown numbers may be anything

It could be done using string functions as follows:
Select Concat(Left(#Var, 2),Replicate('0',Len(#Var)-2))

You can use stuff
declare #x varchar(10)='123456789'
select Stuff(#x,3,10,Replicate('0',Len(#x)-2))

Related

Extract the highest number out of a row of strings

I have data in a #temp_table like this:
SCORM_VARNAME
1) cmi.interactions.0.id
2) cmi.interactions.1.id
3) cmi.interactions.10.id
4) cmi.interactions.5.id
5) cmi.interactions.8.id
etc etc...
In the above example, the number I am ULTIMATELY wanting to save in a variable is 10.
I want to return the highest number that appears in these tables, it can be 0-100000 (I doubt it) but it can't be hardcoded for example. It could only go up to 3!
I have the following code that basically takes whatever string you give it, and CORRECTLY extracts the number, which is great!
DECLARE #string varchar(100)
SET #string = 'cmi.interactions.10.id'
WHILE PATINDEX('%[^0-9]%',#string) <> 0
SET #string = STUFF(#string,PATINDEX('%[^0-9]%',#string),1,'')
SELECT #string
Except I am not sure how to run this function across all the rows in the temp_table and to either replace each row with the highest number, or to return the highest number.
So either I need to figure out a way to return the highest number found in the table, or if you guys could help me by figuring out some way to UPDATE the temp_table, and replacing each string with the number found in it... I would be able to do the rest.
set #v = (
select max(cast(replace(replace(s, 'cmi.interactions.', ''), '.id', '') as int))
from T
);
Late answer ... Just another option is parsename()
Example
Declare #YourTable Table ([SCORM_VARNAME] varchar(50))
Insert Into #YourTable Values
('cmi.interactions.0.id')
,('cmi.interactions.1.id')
,('cmi.interactions.10.id')
,('cmi.interactions.5.id')
,('cmi.interactions.8.id')
Select *
,Value = try_convert(int,parsename(Scorm_Varname,2))
From #YourTable
Returns
SCORM_VARNAME Value
cmi.interactions.0.id 0
cmi.interactions.1.id 1
cmi.interactions.10.id 10
cmi.interactions.5.id 5
cmi.interactions.8.id 8
For the MAX
Select Value = max(try_convert(int,parsename(Scorm_Varname,2)))
From #YourTable

Comma in number with decimal point in SQL Server 2008

I want to put comma in numbers for varchar type with single decimal point with no roundup.
For example:
DECLARE #val varchar(50) = '12345.999'
I want result as :
12,345.9
So far I have tried:
select convert(VARCHAR(15), cast(#val as money), 1)
Result: 12,346.00
but it is doing rounding the value.
Please help. Thanks in advance.
DECLARE #val varchar(50) = '12345.999'
SELECT LEFT(CONVERT(VARCHAR(15),CAST(#val AS MONEY),1),CHARINDEX('.',#val)-3) + SUBSTRING(#val,CHARINDEX('.',#val)-3,5)
Perhaps this will work. Just use the LEFT() function a couple of times after casting to MONEY and VARCHAR
DECLARE #val VARCHAR(50) = '12345.99999'
SELECT LEFT(CONVERT(VARCHAR(15),CAST(LEFT(#val,
CHARINDEX('.',#val,1)+1) AS MONEY),1),CHARINDEX('.',#val,1)+2)
Result:
12,345.9
** Edit **
After thinking about the possibility of having a larger number for the variable, it wouldn't work when there are multiple commas i.e., 123,412,345.999 so I'm editing to include a CASE statement:
DECLARE #val VARCHAR(50) = '123412345.99999'
SELECT LEFT( CONVERT(VARCHAR(15),
CONVERT(MONEY
,LEFT(#val, CHARINDEX('.',#val,1)+1)
,1)
,1)
, CHARINDEX('.',#val)+(CASE
WHEN LEN(LEFT(#val, CHARINDEX('.',#val)-1))>6 THEN 3
ELSE 2
END))

Extract a number after a number pattern in SQL

I am working in SQL server. I have some number like 130-0029. I need to get the integer after the - delimiter out of it. So in this example I need to return 29. These are the following scenarios I have with this,
The pattern may differ like 130-00000029 or 130-0029.
If there are all 0's then print 0, else get actual number like 29.
Please advise/suggest me on this.
Here is an example:
declare #s varchar(100) = '130-0029'
select cast(substring(#s, patindex('%[-]%', #s) + 1, len(#s)) as int)
You may need to cast to some numeric if the number overflows ineteger type.
Try this:
DECLARE #num varchar(50) = '130-0029'
SELECT CAST(SUBSTRING(#num, CHARINDEX('-', #num) + 1, LEN(#num)) AS INT)
Here is a fiddle.
This also works if the - is missing. But if what follows is not a number it will give an error.
declare #string as varchar(100)
set #string = '130-0029'
select convert(int,Right(#string, LEN(#string)-CHARINDEX('-', #string)))
Probably not so different than other answers, but this works using STUFF too:
DECLARE #String VARCHAR(10) = '130-0029';
SELECT CONVERT(INT, STUFF(#String, 1, CHARINDEX('-', #String), ''));
See this running in Query Stack Exchange.

How to make unique random alphanumeric sequence in SQL Server

I want to make unique random alphanumeric sequence to be the primary key for a database table.
Each char in the sequence is either a letter (a-z) or number (0-9)
Examples for what I want :
kl7jd6fgw
zjba3s0tr
a9dkfdue3
I want to make a function that could handle that task!
You can use an uniqueidentifier. This can be generated with the NEWID() function:
SELECT NEWID()
will return something like:
BE228C22-C18A-4B4A-9AD5-1232462F7BA9
It is a very bad idea to use random strings as a primary key.
It will effect performance as well as storage size, and you will be much better of using an int or a bigint with an identity property.
However, generating a random string in SQL maybe useful for other things, and this is why I offer this solution:
Create a table to hold permitted char values.
In my example the permitted chars are 0-9 and A-Z.
CREATE TABLE Chars (C char(1))
DECLARE #i as int = 0
WHILE #i < 10
BEGIN
INSERT INTO Chars (C) VALUES (CAST(#i as Char(1)))
SET #i = #i+1
END
SET #i = 65
WHILE #i < 91
BEGIN
INSERT INTO Chars (C) VALUES (CHAR(#i))
SET #i = #i+1
END
Then use this simple select statement to generate a random string from this table:
SELECT TOP 10 C AS [text()]
FROM Chars
ORDER BY NEWID()
FOR XML PATH('')
The advantages:
You can easily control the allowed characters.
The generation of a new string is a simple select statement and not manipulation on strings.
The disadvantages:
This select results with an ugly name (i.e XML_F52E2B61-18A1-11d1-B105-00805F49916B). This is easily solved by setting the result into a local variable.
Characters will only appear once in every string. This can easily be solved by adding union:
example:
SELECT TOP 10 C AS [text()]
FROM (
SELECT * FROM Chars
UNION ALL SELECT * FROM Chars
) InnerSelect
ORDER BY NEWID()
FOR XML PATH('')
Another option is to use STUFF function instead of As [Text()] to eliminate those pesky XML tags:
SELECT STUFF((
SELECT TOP 100 ''+ C
FROM Chars
ORDER BY NEWID()
FOR XML PATH('')
), 1, 1, '') As RandomString;
This option doesn't have the disadvantage of the ugly column name, and can have an alias directly. Execution plan is a little different but it should not suffer a lot of performance lose.
Play with it yourself in this Sql Fiddle
If there are any more advantages / disadvantages you think of please leave a comment. Thanks.
NewID() Function will generate unique numbers.So i have incremented them with loop and picked up the combination of alpha numeric characters using Charindex and Left functions
;with list as
(
select 1 as id,newid() as val
union all
select id + 1,NEWID()
from list
where id + 1 < 100
)
select ID,left(val, charindex('-', val) - 2) from list
option (maxrecursion 0)
The drawback of NEWID() for this request is it limits the character pool to 0-9 and A-F. To define your own character pool, you have to role a custom solution.
This solution adapted from Generating random strings with T-SQL
--Define list of characters to use in random string
DECLARE #CharPool VARCHAR(255)
SET #CharPool = '0123456789abcdefghijkmnopqrstuvwxyz'
--Store length of CharPool for use later
DECLARE #PoolLength TINYINT
SET #PoolLength = LEN(#CharPool) --36
--Define random string length
DECLARE #StringLength TINYINT
SET #StringLength = 9
--Declare target parameter for random string
DECLARE #RandomString VARCHAR(255)
SET #RandomString = ''
--Loop control variable
DECLARE #LoopCount TINYINT
SET #LoopCount = 0
--For each char in string, choose random char from char pool
WHILE(#LoopCount < #StringLength)
BEGIN
SELECT #RandomString += SUBSTRING(#Charpool, CONVERT(int, RAND() * #PoolLength), 1)
SELECT #LoopCount += 1
END
SELECT #RandomString
http://sqlfiddle.com/#!6/9eecb/4354
I must reiterate, however, that I agree with the others: this is a horrible idea.

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