SQL server triming - sql-server-2008

I am trying to format the licenseenum column in my table by removing everything starting the before space and also I would like to remove any character in licenseenum column starting after '-' including '-'
For example:
current data in Licenseenum GA 350-0
What I'm trying to get 350
Here is my code
select Licenseenum, SUBSTRING (Licenseenum, 4, LEN(Licenseenum)-1)
from licensee
this results
350-0
How would I remove -0 from the results?
Thanks for the help

Try it like this
DECLARE #YourString VARCHAR(100)='GA 350-0';
SELECT SUBSTRING(#YourString,CHARINDEX(' ',#YourString,1),CHARINDEX('-',#YourString,1)-CHARINDEX(' ',#YourString,1));
UPDATE 1
This is quite the same, but better to read
DECLARE #YourString VARCHAR(100)='GA 350-0';
WITH Positions AS
(
SELECT CHARINDEX(' ',#YourString,1) AS posBlank
,CHARINDEX('-',#YourString,1) AS posMinus
)
SELECT SUBSTRING(#YourString,posBlank,posMinus-posBlank)
FROM Positions;
UPDATE 2 Avoid the leading blank...
My logic needs small correction in order to cut the blank before the number:
SELECT SUBSTRING(#YourString,posBlank+1,posMinus-posBlank-1)
Would be the same with the first example...

Please try the below code. Its working fine in SQL Server 2012.
DECLARE #Licenseenum varchar(max)
SET #Licenseenum ='GA 350-0'
DECLARE #TempLicense VARCHAR(100)
DECLARE #License VARCHAR(100)
IF (len(#Licenseenum ) - len(replace(#Licenseenum ,' ',''))>=1)
SET #TempLicense = (SELECT REVERSE(LEFT(REVERSE(#Licenseenum ),CHARINDEX(' ', REVERSE(#Licenseenum ), 1) - 1)))
ELSE
SET #TempLicense = #Licenseenum
SELECT #License = (SELECT LEFT(#TempLicense,LEN(#TempLicense) - charindex('-',reverse(#TempLicense),1)))
SELECT #License AS Licenseenum

Related

Select part of a string between two values SQL 2008

I'm attempting to select a part of a strint between 2 values, i've managed to get it working to about 90% but then get an error -
SUBSTRING(TranText, CHARINDEX('x', TranText) + 1, LEN(TranText) - CHARINDEX('x', TranText) - CHARINDEX('/', REVERSE(TranText)))
The field it is querying is like so
Start Date : 01/02/2013 50 x 156.00/MX + 207.64
with the desired result being
156.00
Now I think the issue is because sometimes the X can have a space before or after it, or no space at all. It gets through about 114,000 rows before throwing
Invalid length parameter passed to the LEFT or SUBSTRING function.
But am struggling to resolve.
The main root cause could be because LEN(#QRY) - CHARINDEX('x', #QRY)-CHARINDEX('/', REVERSE(#QRY)) is less than zero ie, negative value. This in turn will throw error in SUBSTRING since the minimum index for SUBSTRING is zero. Therefore we check that condition in a case statement.
SELECT CASE WHEN LEN(TranText) - CHARINDEX('x',TranText)-CHARINDEX('/', REVERSE(TranText)) >= 0 THEN
SUBSTRING(TranText, CHARINDEX('x', TranText) + 1, LEN(TranText) - CHARINDEX('x', TranText) - CHARINDEX('/', REVERSE(TranText)))
ELSE NULL END
FROM YOURTABLE
Try this. Used REPLACE function and then parsed.
DECLARE #string AS VARCHAR(100), #result AS VARCHAR(100)
DECLARE #nStart AS int
SET #string = 'Start Date : 01/02/2013 50 x 156.00/MX + 207.64'
SET #result = REPLACE(#string, '/', '')
SET #nStart = CHARINDEX('x', #result) + 1
SET #result = SUBSTRING(#result, #nStart, CHARINDEX('M',#result) - #nStart)
SELECT #result

How to Concat data using COALESCE in MySql

This is my SQL query
DECLARE #strManualRefundIdList AS VARCHAR(MAX)
SELECT #strManualRefundIdList = COALESCE(#strManualRefundIdList + '|', '') + CONVERT(VARCHAR(MAX), ManualRefund_strReasonCode)
FROM tblManualRefunds WHERE ManualRefund_lngId IN ( 20 ,21 ,22 )
SELECT #strManualRefundIdList;
This gives like pivot, all the rows concatenated in a single row.
The Same i need to convert into MySql Query.
I tried like this
SELECT
CONCAT(COALESCE(CONCAT(v_strManualRefundIdList, '|'), '') , ( ManualRefund_lngId))
INTO
v_strManualRefundIdList
FROM tblManualRefunds
WHERE Trans_lngId IN ( 20 ,21 ,22 ) ;
But it throws error as Error Code: 1172. Result consisted of more than one row
How to translate that query. I am new to database.
Please help me in figuring out this.
UPDATE :
The way i found out was assigning into a cursor and loop through and concatenate it.
But is that the only way ? or any better way is available ?
SELECT group_concat(ManualRefund_strReasonCode SEPARATOR '|')
FROM tblManualRefunds
WHERE manualRefund_lngId in (20,21,22)
SQL Fiddle
As per xQbert Comment i tried this
SELECT
GROUP_CONCAT(COALESCE(CONCAT('shan', '|'), '') , ( ManualRefund_lngId))
INTO
#v_strManualRefundIdList
FROM tblManualRefunds ;
Its working fine.
Thanks Man.. !!!

summing time column in mysql

I have a column in one of my tables, which is TIME format (00:00:00). I am trying to sum the entire column and display it as same (00:00:00).
I have tried using the following but it is not giving me anywhere near the correct answer.It's giving me 22.12:44:00 and manual calcaulation tells me it should be close to 212:something:something
SELECT SEC_TO_TIME( SUM( TIME_TO_SEC( vluchttijd ) ) ) AS totaltime FROM tbl_vluchtgegevens
Any recommendations?
You can try like this:-
SELECT SEC_TO_TIME(SUM(SECOND(vluchttijd ))) AS totaltime FROM tbl_vluchtgegevens;
or try this(althoug this is not a good approach):
SELECT concat(floor(SUM( TIME_TO_SEC( `vluchttijd ` ))/3600),":",floor(SUM( TIME_TO_SEC( `vluchttijd ` ))/60)%60,":",SUM( TIME_TO_SEC( `vluchttijd ` ))%60) AS total_time
FROM tbl_vluchtgegevens;
Edit:-
Try this:-
select cast(sum(datediff(second,0,dt))/3600 as varchar(12)) + ':' +
right('0' + cast(sum(datediff(second,0,dt))/60%60 as varchar(2)),2) +
':' + right('0' + cast(sum(datediff(second,0,dt))%60 as varchar(2)),2)
from TestTable
Working SQL Fidlle
In MySQL, the TIME type is rather limited in range. Moreover many time function do not accept values greater that 23:59:59, making it really usable only to represent the time of the day.
Given your needs, your best bet is probably to write a custom function that will mimic SEC_TO_TIME but allowing much greater range:
CREATE FUNCTION SEC_TO_BIGTIME(sec INT)
RETURNS CHAR(10) DETERMINISTIC
BEGIN
SET #h = sec DIV 3600;
SET #m = sec DIV 60 MOD 60;
SET #s = sec MOD 60;
RETURN CONCAT(
LPAD(#h, 4, '0'),
':',
LPAD(#m, 2, '0'),
':',
LPAD(#s, 2, '0')
);
END;
And here is how to use it:
create table tbl (dt time);
insert tbl values
('09:00:00'), ('01:00:00'), ('07:50:15'), ('12:00:00'),
('08:30:00'), ('00:45:00'), ('12:10:30');
select SEC_TO_BIGTIME(sum(time_to_sec(dt))) from tbl;
Producing:
+--------------------------------------+
| SEC_TO_BIGTIME(SUM(TIME_TO_SEC(DT))) |
+--------------------------------------+
| 0051:15:45 |
+--------------------------------------+
See http://sqlfiddle.com/#!8/aaab8/1
Please note the result is a CHAR(10) in order to overcome TIMEtype limitations. Depending how you plan to use that result, that means that you may have to convert from that string to the appropriate type in your host language.
This worked for me:
SELECT SEC_TO_TIME(SUM(TIME_TO_SEC(vluchttijd))) AS totaltime FROM tbl_vluchtgegevens;

MySql: updating a column with the column's content plus something else

I'm don't have a lot of knowledge of MySql (or SQL in general) so sorry for the noobness.
I'm trying to update a bunch of String entries this way:
Lets say we have this:
commands.firm.pm.Stuff
Well I want to convert that into:
commands.firm.pm.print.Stuff
Meaning, Add the .print after pm, before "Stuff" (where Stuff can be any Alphanumerical String).
How would I do this with a MySql Query? I'm sure REGEXP has to be used, but I'm not sure how to go about it.
Thanks
Try something like this. It finds the last period and inserts your string there:
select insert(s, length(s) - instr(reverse(s), '.') + 1, 0, '.print')
from (
select 'commands.firm.pm.Stuff' as s
) a
To update:
update MyTable
set MyColumn = insert(MyColumn, length(MyColumn) - instr(reverse(MyColumn), '.') + 1, 0, '.print')
where MyColumn like 'commands.firm.pm.%'
Perhaps use a str_replace to replace commands.firm.pm to commands.firm.pm.print
$original_str = "commands.firm.pm.15hhkl15k0fak1";
str_replace("commands.firm.pm", "commands.firm.pm.print", $original_str);
should output: commands.firm.pm.print.15hhkl15k0fak1
then update your table with the new value...How to do it all in one query (get column value and do the update), I do not know. All I can think of is you getting the column value in one query, doing the replacement above, and then updating the column with the new value in a second query.
To update rows that end in '.Stuff' only:
UPDATE TableX
SET Column = CONCAT( LEFT( CHAR_LENGTH(Column) - CHAR_LENGTH('.Stuff') )
, '.print'
, '.Stuff'
)
WHERE Column LIKE '%.Stuff'
To update all rows - by appending .print just before the last dot .:
UPDATE TableX
SET Column = CONCAT( LEFT( CHAR_LENGTH(Column)
- CHAR_LENGTH(SUBSTRING_INDEX(Column, '.', -1))
)
, 'print.'
, SUBSTRING_INDEX(Column, '.', -1)
)
WHERE Column LIKE '%.%'

How to format int to price format in SQL?

I select the price 1000000 and I need to format it to $1,000,000. How can I do that in SQL?
To format with commas, you can use CONVERT with a style of 1:
declare #money money = 1000000
select '$' + convert(varchar, #money, 1)
will produce $1,000,000.00
If you want to remove the last 3 characters:
select '$' + left(convert(varchar, #money, 1), charindex('.', convert(varchar, #money, 1)) - 1)
and if you want to round rather than truncate:
select '$' + left(convert(varchar, #money + $0.50, 1), charindex('.', convert(varchar, #money, 1)) - 1)
Creating Function:
CREATE FUNCTION [dbo].[f_FormatMoneyValue]
(
#MoneyValue money
)
RETURNS VARCHAR(50)
AS
BEGIN
RETURN cast(#MoneyValue as numeric(36,2))
END
Using in Select Query:
Select dbo.f_FormatMoneyValue(isnull(SalesPrice,0))SalesPrice from SalesOrder
Output:
100.00
Formatting Money Value with '$' sign:
CREATE FUNCTION [dbo].[f_FormatMoneyWithDollar]
(
#MoneyValue money
)
RETURNS VARCHAR(50)
AS
BEGIN
RETURN '$' + convert(varchar, #MoneyValue, 1)
END
Output:
$100.00
Note: The above sample is for the money field. You can modify this function according to your needs
Hope this helps you..! :D
SELECT FORMAT(price, 'C2', 'en-us')
The SQL Server money datatype is just decimal(10, 4). To my knowledge there is no datatype that will present the way you want.
Adding the dollar sign and commas is something that should belong in the application logic, but if you really must do it through a database object consider adding the dollar sign, and commas every three characters (after the decimal point). In other words, you'll have to convert the int to varchar and do string manipulation.
It depends, however, there's no simple way to do it in standard SQL specs(SQL-92, SQL-2003, etc.).
For PostgreSQL PL/pgSQL and Oracle PL/SQL, you can use to_char to format numbers:
select to_char(1234567.123, 'FM$999,999,999.99')
Which gives output:
$1,234,567.12
See: http://www.postgresql.org/docs/7/static/functions2976.htm