T-SQL how to add trailing zeros to a string varchar [closed] - sql-server

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last month.
Improve this question
My number needs to be 8 digits long, however If its less than 8 digits long I need to add trailing zeros to the it.
Example: 1234
Desired result: 12340000
I tried this at first:
DECLARE #YourNumber VARCHAR(8)=1234567;
SELECT DISTINCT
LEFT('00000000'+CAST(ISNULL(#YourNumber,0) AS VARCHAR),8)
However the result is: 00000000

I have the same read as #Hogan +1. I just tend to opt for concat(). No need to test for nulls or even care if the value is a string or int
Example
Select IfInt = left(concat(1234 ,'00000000'),8)
,IfStr = left(concat('1234','00000000'),8)
,IfNull= left(concat(null ,'00000000'),8)
Results
IfInt IfStr IfNull
12340000 12340000 00000000

If what you are asking for is actually what you want then try this:
DECLARE #YourNumber VARCHAR(8)='1234567';
SELECT DISTINCT
LEFT(CAST(ISNULL(#YourNumber,0) AS VARCHAR)+'00000000',8)

Since you are starting with a "number" in a string (DECLARE #YourNumber VARCHAR(8)=1234567;) there is no need to use cast. You can simply add the required number of zeroes:
DECLARE #YourNumber VARCHAR(8)= '1234567'; -- Using a string rather than an Int literal.
select #YourNumber + Replicate( '0', 8 - Len( #YourNumber ) ) as PaddedString;
Aside: It is a best practice to always specify the length of strings, i.e. CAST(ISNULL(#YourNumber,0) AS VARCHAR(8)).

All you have to do is move the "+ '00000000'" portion of the code to the right side of the Cast Function.
DECLARE #YourNumber VARCHAR(8)=1234567;
SELECT DISTINCT
LEFT(CAST(ISNULL(#YourNumber,0) AS VARCHAR)+'00000000',8)
Resulting in final value of: 12345670

Related

Splitting Strings then Creating Segments out of those. T-SQL [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
How do I split a csv string into this format in SQL Server?
Initial String value (A, B, C, D) into :
A-B
B-C
C-D
You can try using string_split in conjunction with lead()
select value + '-' + lead(value) over (order by value) new_value
from string_split('A,B,C,D',',')
SQL FIDDLE:
http://sqlfiddle.com/#!18/0a28f/2607
Grab a copy of NGrams8K then you could simply do this.
DECLARE #string VARCHAR(100) = 'A, B, C, D';
SELECT TheString = CONCAT(ng.Token,'-',ng.Nxt)
FROM
(
SELECT ng.Token, Nxt = LEAD(ng.Token,1) OVER (ORDER BY ng.Position)
FROM dbo.ngrams8k(#string,1) AS ng
WHERE ng.Token LIKE '%[a-z]%'
) AS ng
WHERE ng.Nxt IS NOT NULL;
Returns:
TheString
---------------------
A-B
B-C
C-D
Order is guaranteed without a sort in the execution plan.

ISNULL Not working when I am calculating the sum of two columns in the expression part of the function [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I am trying to use ISNULL (), but in the expression part of the function, instead of having a column name as the argument,I have the sum of four columns, and it should return a 0 when all of the value in the column is NULL, else the sum. for e.g., if three columns have values and corresponding value in the other column is Null, it should still return the sum of the three values. This is how I have written my query:
Select ISNULL([FY18 P1]+[FY18 P2]+[FY18 P3]+[FY18 P4],0) as [Previous YTD]
from TableA
This calculated column inside the ISNULL function is not working. Can anybody help me rewrite this expression so that it will work. What i mean when it is not working is that, it is returning a NULL when only one column is NULL but the rest of the columns have a value. Basically it should return the sum and not NULL in this case.
If any column in your concatenation IS NULL then the result will be NULL.
You need to wrap each column in IS NULL to make this column value 0 so that your addition doesn't return NULL.
SELECT ISNULL([FY18 P1],0) +ISNULL([FY18 P2],0) + ISNULL([FY18 P3],0) + ISNULL([FY18 P4],0)
This is because anything + NULL returns NULL
select 1 + 2 + 3 + NULL --returns `NULL`

Filtering conditional in WHERE clause [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have the PEN_TIPO column of a table, this column can have values 0 and 2, and in the report depending on the filter I apply the condition as follows:
declare #PEN_TIPO int = 0
(A.PEN_TIPO = #PEN_TIPO OR #PEN_TIPO = 0)
However, it will have a condition that I do not need to filter this field, ie I have to get 0 and 2 from the PEN_TIPO column.
How can I apply this filter?
It sounds like you're describing, what is commonly referred to as an optional parameter.
If the user enters a parameter value, they want to filter based on that, if not, ignore it altogether.
It would typically look something like this:
DECLARE #PEN_TIPO INT;
(A.PEN_TIPO = #PEN_TIPO OR #PEN_TIPO IS NULL)
OPTION(RECOMPILE);
Please note that I added "OPTION(RECOMPILE)" to the end of the query.
You'll want to add this to you query too, so that the optimizer can create an optimized plan based on the chosen parameter value.
Are you trying to do this ?
DECLARE #PEN_TIPO INT = NULL
SELECT *
FROM TableName
WHERE
A.PEN_TIPO = ISNULL(#PEN_TIPO, PEN_TIPO)
When #PEN_TIPO = NULL then A.PEN_TIPO = A.PEN_TIPO which will bring everything.
This is usually handled with a similar conditional where clause using NULL, but you code would if you defaulted the value to 1 or another value.
In the below proc, we default the parameter to NULL. It will remain NULL if your report / application doesn't pass in a value.
If it remains null, all rows are returned.
If a value is passed in that is 0 or 2, the filter is applied.
If a value is passed in that isn't 0 or 2, an error is raised.
Here's the proc.
create proc myProc (#PEN_TIPO int = NULL)
as
if (#PEN_TIPO IS NOT NULL) or (#PEN_TIPO NOT IN (0,2))
begin
raiserror('Invalid parameter',16,1)
end
SELECT A.*
FROM SomeTable A
WHERE (A.PEN_TIPO = #PEN_TIPO OR #PEN_TIPO IS NULL)
Aaron Bertrand has an in-depth post on these Kitchen Sink type queries.

SQL Server how to get money type's decimal digits? [duplicate]

This question already has answers here:
Get the number of digits after the decimal point of a float (with or without decimal part)
(6 answers)
Closed 4 years ago.
The column CostPrice of table t1 is money type.
The data in column CostPrice likes this:
141.1938
0.00
147.1041
119.592
1.23
I use this sql to get the decimal digits:
select distinct len(CostPrice-floor(CostPrice))-2 from t1;
But the result is only 2,this is not right,in fact,the result should be 2,3,4.
So how to fix the sql?
Added:
StackOverflow does not allow me to flag the flagging but asked me to edit the question instead, so:
This Question is not a duplicate to this one. The existing question is on the "float" datatype and this one is on "money", Converting "money" to "varchar" like in the "existing anser" will always return the same number of decimal places, so it does not answer this question.
You could (independantly from regional settings):
multiply the value by 10,000
convert the result to integer
convert the integer to a string
add 4 leading zeroes to the left (just in case...)
take the 4 characters from the right (the former decimal places)
replace each zero by a blank character
remove the trailing blanks using rtrim
return the length of the remaining string
To put this in an expression, it would be:
LEN(RTRIM(REPLACE(RIGHT('0000' + CONVERT(varchar(20), CONVERT(int, CostPrice*10000)), 4), '0', ' ')))
Try this
DECLARE
#money money = 141.1938
SELECT
#money
,SUBSTRING(CONVERT(varchar(20),#money,2), CHARINDEX('.', CONVERT(varchar(20),#money,2)) + 1, LEN(CONVERT(varchar(20),#money,2))) as RESULT

Can someone tell me the mistake in this sql code? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Declare #Random int = 1, #Bool bit = 0;
WHILE (#Bool = 0)
BEGIN
SET #Random = ROUND(RAND()*(SELECT MAX(CharID) FROM SRO_VT_SHARD_INIT.dbo._Char where LastLogout < DATEADD(DAY, -3, CURRENT_TIMESTAMP),0)
IF exists (SELECT CharID FROM SRO_VT_SHARD_INIT.dbo._Char WHERE CharID = #Random)
BEGIN
SET #Bool = 1 /*true*/
END
END
print #Random
It gives and error after the CURRENT_TIMESTAMP it says that there is an syntax error near the comma. If I remove the ,0 then the ROUND function doesn't have enough arguments. Someone?
Change
CURRENT_TIMESTAMP),0)
to
CURRENT_TIMESTAMP)),0)

Resources