how to convert numeric to nvarchar in sql command - sql

I need to convert a numeric value to nvarchar in sql command.
Can anyone please help me.

select convert(nvarchar(255), 4343)
Should do the trick.

declare #MyNumber int
set #MyNumber = 123
select 'My number is ' + CAST(#MyNumber as nvarchar(20))

declare #MyNumber float
set #MyNumber = 123.45
select 'My number is ' + CAST(#MyNumber as nvarchar(max))

If the culture of the result doesn't matters or we're only talking of integer values, CONVERT or CAST will be fine.
However, if the result must match a specific culture, FORMAT might be the function to go:
DECLARE #value DECIMAL(19,4) = 1505.5698
SELECT CONVERT(NVARCHAR, #value) --> 1505.5698
SELECT FORMAT(#value, 'N2', 'en-us') --> 1,505.57
SELECT FORMAT(#value, 'N2', 'de-de') --> 1.505,57
For more information on FORMAT see here.
Of course, formatting the result should be a matter of the UI layer of the software.

Related

Convert binary to varchar

I need to change the binary output to varchar(string), but it must same as to be the binary output. But while converting the binary(hex) value to varchar, empty set will be returned. Kindly help me.
E.x
If this is my binary value 0x24000000008B0100000000.
I need the same 0x24000000008B0100000000 output after converting it into string.
declare #val binary(20)
set #val=0x24000000008B0100000000
select #val, CONVERT(varchar(max),#val,1)
this also works for me :
SELECT CONVERT(VARCHAR(1000), varbinary_val, 1);
just change your value with varbinary_val
should work like:
DECLARE #a BINARY(20) = 0x24000000008B0100000000
SELECT CONVERT(varchar(max),#a,1), #a

Remove only zero after decimal sql server 2012

Consider the following numbers.
7870.2
8220.0
I need to remove decimal points if the value ends with .0. If it ends with .2 then it should keep the value as it is.
I have used ceiling but it removes all the values after decimal.
How can I write a select query in which I can add some condition for this?
Generally speaking you should not do this in your dB. This is an app or reporting side operation. The dB is made to store and query information. It is not made to format/string manipulate information.
use right within a case statement and:
DECLARE #val decimal(5,1)
SET #val = 7870.0
Select
Case
When right(#val,1)<> '0' then
cast(#val as varchar)
else
cast(cast(#val as int) as varchar)
End
output: 7870
EDIT: I could write :
Case
When right(#val,1)<> '0' then
#val
else
cast(#val as int) -- or floor(#val)
End
but because return type of case statement is the highest precedence type from the set of given types, so the output for second version is: 7870.0 not 7870, that's why I convert it to i.e varchar in when clauses, and it can be converted outside of case statement, I mean cast ((case when...then...else... end) as datatype)
Cast the number as a float, using float(24) to increase precision:
DECLARE #t table(number decimal(10,1))
INSERT #t values(7870.2),(8220.0)
SELECT cast(number as float(24))
FROM #t
Result:
7870,2
8220
Here below goes a sample:
declare #1 decimal(4,3)
select #1 = 2.9
select case when SUBSTRING (PARSENAME(#1,1), 1, 1) = 0 then FLOOR(#1) else #1 end
Change the #1 in the select statement with your database field name.
sqlfiddle
The solution seems to be simple:
SELECT CONVERT (FLOAT, PAYLOAD)

SQL - Cut string upto a string (first one only)

i have a string like this:
DECLARE #val nvarchar(max)
set #val='id=1 and Name=abc and Address=NY and age=32'
Now i need to cut the string only upto the end of first and.here id length can be 1-100000.So i can fixed a length.
Current situation: id=1 and Name=abc and Address=NY and age=32
Expected result: Name=abc and Address=NY and age=32
Thanks in advance
DECLARE #val NVARCHAR(MAX)
SET #val='id=1 and Name=abc and Address=NY and age=32'
SELECT SUBSTRING(#val, PATINDEX('% and%', #val) + 4, LEN(#val))
SQLFiddle Demo
Other Links
PATINDEX()
LEN()
SUBSTRING()
DECLARE #val nvarchar(max)
DECLARE #val1 int
set #val='id=1 and Name=abc and Address=NY and age=32'
set #val1=CHARINDEX('Name', #val)
select val2=SUBSTRING(#val,#val1,LEN(#val)-(#val1-1))
If I understand correctly what you are after something like this should get you want you want:
substring(#val , CHARINDEX(#val) + 4, len(#val))
I guess we can also do it without a call of LEN and SUBSTRING method.
Something like this would help:
DECLARE #val nvarchar(max)
set #val='id=1 and Name=abc and Address=NY and age=32'
Select #val as OriginalValue
select stuff(#val,1,charindex('d ',#val) + 1,'') as ExpectedResult
We need a call of STUFF method along with CHARINDEX.
Check out how STUFF works.
Remember: STUFF is position oriented (starts with 1).
Here is the output:
use substring function like
#val=substring('#val',9,'remaining char')
see: SUBSTRING(), CHARINDEX(), PATINDEX()
refer here
http://www.sqlinfo.net/sqlserver/sql_server_function_substring.php

How to convert Varchar to Int in sql server 2008?

How to convert Varchar to Int in sql server 2008.
i have following code when i tried to run it wont allowed me to convert Varchar to Int.
Select Cast([Column1] as INT)
Column1 is of Varchar(21) NOT NULL type and i wanted to convert it into Int.
actually i am trying to insert Column1 into another table having Field as INT.
can someone please help me to convert this ?
Spaces will not be a problem for cast, however characters like TAB, CR or LF will appear as spaces, will not be trimmed by LTRIM or RTRIM, and will be a problem.
For example try the following:
declare #v1 varchar(21) = '66',
#v2 varchar(21) = ' 66 ',
#v3 varchar(21) = '66' + char(13) + char(10),
#v4 varchar(21) = char(9) + '66'
select cast(#v1 as int) -- ok
select cast(#v2 as int) -- ok
select cast(#v3 as int) -- error
select cast(#v4 as int) -- error
Check your input for these characters and if you find them, use REPLACE to clean up your data.
Per your comment, you can use REPLACE as part of your cast:
select cast(replace(replace(#v3, char(13), ''), char(10), '') as int)
If this is something that will be happening often, it would be better to clean up the data and modify the way the table is populated to remove the CR and LF before it is entered.
you can use convert function :
Select convert(int,[Column1])
That is how you would do it, is it throwing an error? Are you sure the value you are trying to convert is convertible? For obvious reasons you cannot convert abc123 to an int.
UPDATE
Based on your comments I would remove any spaces that are in the values you are trying to convert.
That is the correct way to convert it to an INT as long as you don't have any alpha characters or NULL values.
If you have any NULL values, use
ISNULL(column1, 0)
Try the following code. In most case, it is caused by the comma issue.
cast(replace([FIELD NAME],',','') as float)
Try with below command, and it will ask all values to INT
select case when isnumeric(YourColumn + '.0e0') = 1
then cast(YourColumn as int)
else NULL
end /* case */
from YourTable
There are two type of convert method in SQL.
CAST and CONVERT have similar functionality. CONVERT is specific to SQL Server, and allows for a greater breadth of flexibility when converting between date and time values, fractional numbers, and monetary signifiers. CAST is the more ANSI-standard of the two functions.
Using Convert
Select convert(int,[Column1])
Using Cast
Select cast([Column1] as int)

Is there any simple way to format decimals in T-SQL?

I know it could be done trivially in a non-SQL environment [post-data processing, frontend, what have you], but that's not possible at the moment. Is there a way to take a decimal(5,2) and convert it to a varchar without the trailing zeroes/decimal points? For example:
declare #number decimal(5,2)
set #number = 123.00
select cast(#number as varchar) as FormattedNumber
And the result is '123.00'. Is there a (simple) way to get '123' instead? And likewise, instead of '123.30', '123.3'? Could do it by figuring out whether or not the hundredths/tenths places were 0 and manually trimming characters, but I wanted to know if there was a more elegant solution.
What about:
SELECT CAST(CAST(#number AS float) AS varchar(10))
However you may want to test this carefully with your raw data first.
This way is pretty simple:
DECLARE #Number DECIMAL(5,2)
SELECT #Number = 123.65
SELECT FormattedNumber = CAST(CAST(#Number AS DECIMAL(3,0)) AS VARCHAR(4))
Returns '124'.
The only thing to consider is whether you want to round up/down, or just strip the zeroes and decimal points without rounding; you'd cast the DECIMAL as an INT in the second case.
For controlled formatting of numbers in T-SQL you should use the FORMAT() function. For example:
DECLARE #number DECIMAL(9,2); SET #number = 1234567.12;
DECLARE #formatted VARCHAR(MAX); SET #formatted = FORMAT(#number, 'N0', 'en-AU');
PRINT #formatted;
The result will be:
1,234,567
The arguments to the FORMAT() function are:
FORMAT(value, format [, culture])
The value argument is your number. The format argument is a CLR type formatting string (in this example, I specified "normal number, zero precision"). The optional culture argument allows you to override the server culture setting to format the number as per a desired culture.
See also the MSDN ref page for FORMAT().
The Convert function may do what you want to do.
ms-help://MS.SQLCC.v9/MS.SQLSVR.v9.en/tsqlref9/html/a87d0850-c670-4720-9ad5-6f5a22343ea8.htm
Let me try this again....
CREATE FUNCTION saneDecimal(#input decimal(5,2)) returns varchar(10)
AS
BEGIN
DECLARE #output varchar(10)
SET #output = CAST(#input AS varchar(10))
DECLARE #trimmable table (trimval char(1))
INSERT #trimmable VALUES ('0')
INSERT #trimmable VALUES ('.')
WHILE EXISTS (SELECT * FROM #trimmable WHERE trimval = CAST(SUBSTRING(#output, LEN(#output), 1) AS char(1)))
SET #output = LEFT(#output, LEN(#output) - 1)
RETURN #output
END
GO
SELECT dbo.saneDecimal(1.00)
You could strip the trailing zeroes in a while loop:
declare #number decimal(5,2)
declare #str varchar(100)
set #number = 123.00
set #str = #number
while substring(#str,len(#str),1) in ('0','.',',')
set #str = substring(#str,1,len(#str)-1)
But as AdaTheDev commented, this is more easily done client-side.
Simple and elegant? Not so much...but that's T-SQL for you:
DECLARE #number decimal(5,2) = 123.00
DECLARE #formatted varchar(5) = CAST(#number as varchar)
SELECT
LEFT(
#formatted,
LEN(#formatted)
- PATINDEX('%[^0.]%', REVERSE(#formatted))
+ 1
)
Use the Format(value,format string,culture) function in SQL Server 2012+
If you have SQL Server 2012 or Greater you can use the format function like this:
select format(#number,'0') as FormattedNumber
Of course the format function will return an nvarchar, and not a varchar. You can cast to get a specific type.
Also, take a look at the T-SQL STR function in Books Online; this can be used for formatting floats and might work for your case. For some reason it doesn't come up in Google searches relating to this problem.