T sql cast string value as money format not working - sql-server

I have values as string format below,
Values :
-24,52
-22,74
-13,08
303,75
When i convert above string values as money all values displays as below
-2452,00
-2274,00
-1308,00
30375,00
All values have more "0" number problem.How can i convert string values to exact money format ?

You can try to remove the 00 like this:
select replace(convert(varchar,cast(yourNum as money),1), ',00','')
Or in SQL Server 2012 you can try to use FORMAT
SELECT Format(24.01, '##,##0')

select cast('-24,01' as money) / 100
For anything other than visual presentation its a good idea to avoid MONEY entirely.

try this query
WITH t
AS
(
SELECT -24.52 AS [val]
UNION
SELECT -22.74
UNION
SELECT -13.08
UNION
SELECT 303.75
)
SELECT CAST( ABS(t.val) AS decimal(10,2)) -- or decimal(10,0)
FROM t

i tried to replace the comma with a point and got lucky:
cast(replace('-12,23', ',', '.') as money)
the reason is, sql server treats ',' as thousend delimiter instead of decimal delimiter

Related

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

How do you write a SQL query to find all the rows that has a float currency value like $15.34 in a nvarchar field

How do you write a SQL query to find only the rows that has a float currency value like $15.34 and NOT round currency value like 15 in a nvarchar field.
Assuming you have a mix of numeric and non-numeric, this should work to return all decimal values that are not whole dollar amounts:
Select * from tablename
where colname like '%.%' --Has a decimal (as in original query)
and colname not like '%.00' --Does not end with 00
It is as simple as
Select * from tablename where columnname = '15.34'
I would strip the $ out, and check if it evaluates to a numeric or not, and use a modulo to be sure a remainder remains when divided by 1.
DECLARE #TEST TABLE (columnname NVARCHAR(15))
INSERT INTO #TEST
SELECT '$15.34' UNION
SELECT 'ZERO' UNION
SELECT '$123.00'
SELECT *, CONVERT(MONEY,REPLACE(columnname,'$',''))
FROM #TEST
WHERE ISNUMERIC(REPLACE(columnname,'$',''))=1
AND CONVERT(MONEY,REPLACE(columnname,'$','')) % 1 != 0
You can use like
Select * from Yourtablename where Yourcolumnname like '$15.%'
Two things:
First, you want to find the rows having the $ in them.
WHERE LOCATE('$',columname) <> 0
Second, you want to find the rows where the rest of the value in the column is a floating point number.
AND CONVERT(REPLACE(columnname,'$',''),DECIMAL(10,2)) <> 0
That CONVERT() <>0 pattern works because MySQL silently returns zero when you try to convert a nonnumeric value to a number.

SQL Server Conversion error: Conversion failed when converting the nvarchar value 'XXX' to data type int

Running some pretty simple SQL here:
select *
from table
where columnA <> convert(int,columnB)
and isnumeric(columnB) = 1
Still getting this error every time:
Conversion failed when converting the nvarchar value 'XXX' to data type int.
If you're using SQL Server 2012 or more recent you could use TRY_PARSE which will return NULL when the parse fails.
SELECT TRY_PARSE('one' as int) -- NULL
, TRY_PARSE('1' as int) -- 1
, TRY_PARSE('0.1' as int) -- NULL
Returns the result of an expression, translated to the requested data type, or null if the cast fails in SQL Server. Use TRY_PARSE only for converting from string to date/time and number types.
Isnumeric has a lot of odd behavior. For example, it also considers currency signs such as $ or £, and even a hyphen (-) to be numeric.
I think you'd be better of using NOT columnB like '%[^0-9]%' to ONLY take numbers into account.
Check the comments at the bottom of the msdn page for isnumeric(), which you can find here: https://msdn.microsoft.com/en-us/library/ms186272.aspx
This may sound weird, but it breaks when do not put the ISNUMERIC check first. Try this out:
WITH [Table]
AS
(
SELECT columnA,columnB
FROM
(
VALUES (1,'2'),
(2,'XXX')
) A(columnA,columnB)
)
select *
from [Table]
where ISNUMERIC(columnB) = 1 --this works
AND columnA <> convert(int,columnB)
--where columnA <> convert(int,columnB) --this doesn't work
-- and isnumeric(columnB) = 1
I suggest you to reverse your checking like this:
SELECT *
FROM table
WHERE CONVERT(NVARCHAR, columnA) <> columnB
I got this using a combination of the answers and comments here. I used a CASE statement in my WHERE clause and also had to use LIKE instead of ISNUMERIC to account for illegal characters. I also had to use BIGINT because a few select samples were overflowing the INT column. Thanks for all of the suggestions everybody!
select * from patient
where PatientExternalID <>
(case when mrn not like '%[^0-9]%'
then convert(bigint, mrn)
else 0
end)

Special Character in SQL

I have a problem with a special character inserted in a table of SQL Server 2008 R2.
The point is that when i'm trying to insert a string with the character º (e.g. 3 ELBOW 90º LONG RADIUS) in the table this appears like this: 3 ELBOW 90� LONG RADIUS, and when i'm trying to select all the rows that contains the character � the result is null.
I tried to make the select with ASCII by making this:
select * from itemcode where description like '%'+char(63)+'%'
and make this to know that the ASCII of that symbol is 63:
select ASCII('�')
But that doesn't work.
What i must do to select all the rows that have that character and what should i do to make that SQL recognize the character º?
Thanks
The degree symbol
U+00B0 ° degree sign (HTML: ° °)
is not an ASCII character and generally requires an NVARCHAR column and a N'' string literal. (except for codepages etc that support the symbol)
63 is the code of the question mark, which is the fallback for your inverse question mark in ASCII:
select UNICODE('�') => 63
select UNICODE(N'�') => 65533
where 65533 is the Unicode Replacement Character used to display characters that could not be converted or displayed.
when I run this:
print ascii('º')
I get 186 as the ascii code value, so try:
select * from YourTable Where Description like '%'+char(186)+'%'
to see all the ascii codes run this:
;WITH AllNumbers AS
(
SELECT 1 AS Number
UNION ALL
SELECT Number+1
FROM AllNumbers
WHERE Number<255
)
SELECT Number,CHAR(Number) FROM AllNumbers
OPTION (MAXRECURSION 255)
EDIT op stated in a comment that they are using nvarchar columns.
forger about ascii, use NCHAR (Transact-SQL) to output a degree symbol:
print '32'+NCHAR(176)+'F' --to display it
select * from YourTable
Where Description like '%'+NCHAR(176)+'%' --to select based on it
and use UNICODE (Transact-SQL) to get the value:
print UNICODE('°')
returns:
176
select top 10 * from table_name
where tbl_colmn like N'%'+ NCHAR(65533) + N'%'
the function NCHAR(65533) will return the character your're looking for.
In addition to making sure that it is an NVARCHAR, I would use something like this
select (N'�')
How to display special characters in SQL server 2008?
I know this is old, but recently faced the same problem, and found solution here
"The best way I know of to find it or get rid of it in SQL is to check for it using a binary collation. For example"
Declare #Foo Table(PK int primary key identity, MyData nvarchar(20));
Insert #Foo(MyData) Values (N'abc'), (N'ab�c'), (N'abc�')
Select * From #Foo Where MyData Like N'%�%'
-- Find rows with the character
Select * From #Foo
Where CharIndex(nchar(65533) COLLATE Latin1_General_BIN2, MyData) > 0
-- Update rows replacing character with a !
Update #Foo
set MyData = Replace(MyData, nchar(65533) COLLATE Latin1_General_BIN2, '!')
Select * From #Foo

Reporting Services - String Length being changed with UNION ALL T-SQL

I have one data_source returning 2 rows from a query with one string with 8chars and another with 11chars. I'm really sure that one of the strings has 8 chars because i explicit put it in the where condition( something like this . where name = 'ftcc_ppp') .The truth is that reporting services is adding some extra blank chars and is fixing the length of the string to the max(length string of all the resultset without the where condition).
I wanted to make some filters and was having the wrong results because the string was not with 8 chars, but instead with 11 chars(8 + 3blank).
The where condition is done in a sub-query that has in that field one row with 8 chars and another with 11 chars(ftcc_ppp and ftcc_ppp_lx).
why reporting services act like this ? Any explanation?
Thank you all
EDIT: Query code:
BEGIN
DECLARE #dtDate DATETIME
DECLARE #lastDay DATE;
DECLARE #firstDay DATE;
DECLARE #currentDate DATE;
DECLARE #month_table AS TABLE(DATA DATE);
SET #dtDate = #DATA;
SET #lastDay = CAST(DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,#dtDate)+1,0)) AS DATE)
SET #firstDay = DATEADD(d,-DAY(#dtDate)+1,#dtDate);
SET #currentDate = #firstDay;
WHILE #currentDate <> dateadd(d,1,#lastDay)
BEGIN
PRINT #currentDate;
INSERT INTO #month_table VALUES(#currentDate);
SET #currentDate = dateadd(d,1,#currentDate);
END
SELECT * FROM (
SELECT DATA,motivo,SUM(total) AS total,CAST(campanha AS VARCHAR(11)) AS campanha,[TYPE]
FROM [Client].[dbo].[ftcc_ppp_motivo_nelegivel_totais]
GROUP BY DATA,motivo,campanha,[TYPE]
UNION ALL
SELECT DATA,motivo,0 AS total,CAST('ftcc_ppp' AS VARCHAR(11)) campanha,'LOP' AS [TYPE]
FROM #month_table
CROSS JOIN dbo.ftcc_ppp_motivo_nelegivel_keys
UNION ALL
SELECT DATA,motivo,0 AS total,CAST('ftcc_ppp' AS VARCHAR(11)) campanha,'ALOP' AS [TYPE]
FROM #month_table
CROSS JOIN dbo.ftcc_ppp_motivo_nelegivel_keys
UNION ALL
SELECT DATA,motivo,0 AS total,CAST('ftcc_ppp_lx' AS VARCHAR(11)) campanha,'CARD' AS [TYPE]
FROM #month_table
CROSS JOIN dbo.ftcc_ppp_motivo_nelegivel_keys
) xpto
WHERE campanha = 'ftcc_ppp'
END
I found the issue!! :) :)
The problem was in the hardcoded string.
Apparently hardcoded strings is a char type. So i had one char with 8 plus one char with 11.
The result obvious was 11 chars.
Using the len() in SQL SERVER i couldn't find the blank spaces inserted because SQLSERVER automatically removes the blank chars. When editing the rows inside SQL SERVER the cursor shown me the blank spaces. Great Lesson :)
Thank you all for the time given to my problem.
It was a pleasure to utilize for the first time StackOverflow.
Thank you all.
Greetings.
Another possible cause: Check your database compatibility level. If set to 80 you may have an issue, but 90 (or higher?) you wouldn't.
According to:
http://msdn.microsoft.com/en-us/library/bb510680.aspx
The UNION of a variable-length column and a fixed length column
produces a fixed-length column.

Resources