sql prepend entries - sql

I have some entries that are inconstant, they should be prepended by the same string.
some have numbers and other have the dollar sign and the number
so I have a syntax that finds all the entries which do not have the dollar sign
WHERE [mydata] not like '$%'
how do I add the string before each entry?

update table set mydata = '$' + mydata where [mydata] not like '$%'
The + only works in SQLServer; you may need to use the concatenate function otherwise.

If you are looking for just a select statement to return the value with a $, this will work:
Select '$' + field
from [table]
where field not like '$%'
You can run it as a case statement had you wanted both records that have a $ and those without to be returned with the $
Select case when left(field,1) = '$' then '' else '$' end + field
from [table]
where field not like '$%'
edit: Might need to convert the 'field' into a varchar for the + to work, you'll get a syntax error if the field is an int (but you have the $ spuradically in the field, so I assumed it's a varchar

Related

Replacing empty string in SQL using SELECT

I'm trying to replace empty strings with a value and I can't seem to find the best way to do this.
The issue is that SOME values in the phone_number column are in a format without the numbers. For example ( ) -
I want to replace those empty values with 000-0000. I tried to use the CASE WHEN function but that doesn't seem to address the problem. The COALESCE IFNULL won't work because technically the values aren't NULL just incomplete. I'm thinking perhaps the CASE WHEN function would work if I could figure out how to format the empty values correctly.
Here is an example of the code
SELECT
phone_column,
CASE
WHEN phone_column = '() -'
THEN '000-000'
ELSE SUBSTRING(phone_colum, 6, 8)
END AS Phone
FROM
client_table
ORDER BY
linkid_
declare #test table(ph varchar(20))
insert into #test
select '( ) -'
UNION
select ''
UNION
select '(123)-456-7890'
select case
when replace(ph,'( ) -','')='' then '000-000'
else substring(ph,6,8)
end
from #test
if you want to search in a varchar then use LIKE this would help you in using expressions. For instance, in your case phone_column = '() -' would be phone_column LIKE '() -%' this will match any string that begins with () -. if you do phone_column = '() -' then it will only match the exact same string.
Any how, I'm not sure why you want to take this road, while you can validate the current numbers and try to only store the valid ones, as storing invalid numbers would be useless.
I'll give you an example,
to validate phone numbers, you first take out any existed formats (parentheses, dashes, spaces) then you'll be end up with a whole number with 10 or 7 digits. depends on your way of storing phone numbers. any numbers less than that would be invalid.
To remove the formats :
SELECT REPLACE(REPLACE(REPLACE(REPLACE(Number,'(',''),')',''),'-',''),' ','')
Now you will have only numbers, which will be easier to handle.
Like this :
SELECT
phone_column
FROM (SELECT REPLACE(REPLACE(REPLACE(REPLACE(phone_column,'(',''),')',''),'-',''),' ','') phone_column FROM client_table) D
PS : Some countries phone numbers begins with 0, if your numbers don't
begin with 0, then you would cast the number to BIGINT, which will
remove any leading zeros.
Now, you can use the case to validate the numbers and do whatever you like with them.
SELECT
CASE
WHEN LEN(phone_column) = 10
THEN '(' + SUBSTRING(phone_column,1,3) + ') ' + SUBSTRING(phone_column, 3,3) + '-' + SUBSTRING(phone_column, 6,4)
ELSE '(000) 000-0000'
END Phone
FROM (SELECT REPLACE(REPLACE(REPLACE(REPLACE(phone_column,'(',''),')',''),'-',''),' ','') phone_column FROM client_table) D

SQL: How to make a replace on the field ''

I have a very but tricky question for you guys. So, listen I have a field with spaces and numbers in one of my table columns. The key part is transform the content in a decimal field. The drawback is basically that for some rows I could get something like:
' 1584.00 '
' 156546'
'545.00 '
' '
So, to clean up my column, I have done a LTRIM and RTRIM so spaces gone. So now for a couple of records where the record were just spaces the new content is ''. Finally I need to convert this result to a decimal.
Issue: The thing is that for field that contend just the spaces the new result is '' and I'm not able to apply a REPLACE on this because it's a blank and the code below doesn't work:
SELECT REPLACE('','','0')
-- Final current verison
SELECT CAST(COALESCE(REPLACE(REPLACE([Gross_Weight],' ','0'),',',''),'0') AS DECIMAL(13,3))
How could I figure it out?
thanks so much
SELECT COALESCE(NULLIF(MyColumn, ''), 0)
This has the side-effect that you will also turn NULL values into 0, which you might not want. If that's a problem then a simple CASE statement should do the trick:
SELECT CASE WHEN MyColumn = '' THEN 0 ELSE CAST(MyColumn AS DECIMAL(10, 4)) END
Obviously you'll also have to incorporate any other manipulations that you're already doing.
No need for replace, just concatenate a zero to your column, like
SELECT RTRIM('0' + LTRIM(column))
I presume your data is in a table.
Lets call this table 'DATA' and the column 'VALUE'
Then you might use the below query
UPDATE DATA SET VALUE = 0 where VALUE = ''
To select the value do the below
select case ltrim(rtrim([Gross_Weight])) when ''
THEN 0
ELSE ltrim(rtrim([Gross_Weight])) END
Let me know if i get the requirement wrong.

SQL SELECT WHERE string ends with Column

I have this table in SQL Server 2012:
Id INT
DomainName NVARCHAR(150)
And the table have these DomainName values
google.com
microsoft.com
othersite.com
And this value:
mail.othersite.com
and I need to select the rows where the string ends with the column value, for this value I need to get the row no.3 othersite.com
It's something like this:
DomainName Like '%value'
but in reverse ...
'value' Like %DomainName
You can use such query:
SELECT * FROM TABLE1
WHERE 'value' LIKE '%' + DomainName
It works on mysql server. [ LIKE '%' || value ] not works great because when value start with numbers this like not return true.
SELECT * FROM TABLE1 WHERE DomainName like CONCAT('%', value)
In Oracle you can use REGEXP_LIKE string function for string start/ends with search. This function 1st argument is an expression/source string and 2nd argument is a pattern/search string. Use dollar $ for a ends with value and ^ for starts with value. For example
select * from TABLE1 where REGEXP_LIKE(DomainName, :value ||'$');
If you have a OR condition between different values, then use following pipe | syntax.
select * from TABLE1 where REGEXP_LIKE(DomainName, 'value1$|value2$|value2$');
Refer this link for more info on REGEXP_LIKE string function

Detect \n character saved in SQLite table?

I designed a table with a column whose data contains \n character (as the separator, I used this instead of comma or anything else). It must save the \n characters OK because after loading the table into a DataTable object, I can split the values into arrays of string with the separator '\n' like this:
DataTable dt = LoadTable("myTableName");
DataRow dr = dt.Rows[0]; //suppose this row has the data with \n character.
string[] s = dr["myColumn"].ToString().Split(new char[]{'\n'}, StringSplitOptions.RemoveEmptyEntries);//This gives result as I expect, e.g an array of 2 or 3 strings depending on what I saved before.
That means '\n' does exist in my table column. But when I tried selecting only rows which contain \n character at myColumn, it gave no rows returned, like this:
--use charindex
SELECT * FROM MyTable WHERE CHARINDEX('\n',MyColumn,0) > 0
--use like
SELECT * FROM MyTable WHERE MyColumn LIKE '%\n%'
I wonder if my queries are wrong?
I've also tested with both '\r\n' and '\r' but the result was the same.
How can I detect if the rows contain '\n' character in my table? This is required to select the rows I want (this is by my design when choosing '\n' as the separator).
Thank you very much in advance!
Since \n is the ASCII linefeed character try this:
SELECT *
FROM MyTable
WHERE MyColumn LIKE '%' || X'0A' || '%'
Sorry this is just a guess; I don't use SQLite myself.
Maybe you should just be looking for carriage returns if you arent storing the "\n" literal in the field. Something like
SELECT *
FROM table
WHERE column LIKE '%
%'
or select * from table where column like '%'+char(13)+'%' or column like '%'+char(10)+'%'
(Not sure if char(13) and 10 work for SQLite
UPDATED: Just found someone's solution here They recommend to replace the carriage returns
So if you want to replace them and strip the returns, you could
update yourtable set yourCol = replace(yourcol, '
', ' ');
The following should do it for you
SELECT *
FROM your_table
WHERE your_column LIKE '%' + CHAR(10) + '%'
If you want to test for carriage return use CHAR(13) instead or combine them.
I've found a solution myself. There is few way (with some dedicated function) to convert ascii code to symbol in SQLite at the moment (CHAR function is not support and using '\n' or '\r' directly doesn't work). But we can convert using CAST function and passing in a Hex string (specified by append X or x before the string) in SQLite like this:
-- use CHARINDEX
SELECT * FROM MyTable WHERE CHARINDEX(CAST(x'0A' AS text),MyColumn,0) > 0
-- use LIKE
SELECT * FROM MyTable WHERE MyColumn LIKE '%' || CAST(x'0A' AS text) || '%'
The Hex string '0A' is equal to 10 in ascii code (\r). I've tried with '0D' (13 or '\n') but it won't work. Maybe the \n character is turned to \r after being saved in to SQLite table.
Hope this helps others! Thanks!

sql in clause doesn't work

I have a table with a column ancestry holding a list of ancestors formatted like this "1/12/45". 1 is the root, 12 is children of 1, etc...
I need to find all the records having a specific node/number in their ancestry list. To do so, I wrote this sql statement:
select * from nodes where 1 in (nodes.ancestry)
I get following error statement: operator does not exist: integer = text
I tried this as well:
select * from nodes where '1' in (nodes.ancestry)
but it only returns the records having 1 in their ancestry field. Not the one having for instance 1/12/45
What's wrong?
Thanks!
This sounds like a job for LIKE, not IN.
If we assume you want to search for this value in any position, and then we might try:
select * from nodes where '/' + nodes.ancestry + '/' like '%/1/%'
Note that exact syntax for string concatenation varies between SQL products. Note that I'm prepending and appending to the ancestry column so that we don't have to treat the first/last items in the list differently than middle items. Note also that we surround the 1 with /s, so that we don't get false matches for e.g. with /51/ or /12/.
In MySQL you could write:
SELECT * FROM nodes
WHERE ancestry = '1'
OR LEFT(ancestry, 2) = '1/'
OR RIGHT(ancestry, 2) = '/1'
OR INSTR(ancestry, '/1/') > 0
The in operator expects a comma separated list of values, or a query result, i.e.:
... in (1,2,3,4,5)
or:
... in (select id from SomeOtherTable)
What you need to do is to create a string from the number, so that you can look for it in the other string.
Just looking for the string '1' in the ancestry list would give false positives, as it would find it in the string '2/12/45'. You need to add the separator to the beginning and the end of both strings, so that you look for a string like '/1/' in a string like '/1/12/45/':
select * from nodes
where charindex('/' + convert(varchar(50), 1) + '/', '/' + nodes.ancestry + '/') <> 0