Using ' in Query String - sql

I have a query that I want to be able to match strings containing '. I currently have:
QUERY(nameGen!$A$1:$G500, "SELECT D WHERE B matches '"&$B1091&"'",0)
So it's the cell reference &$B1091& that will contain the string

Got it. Needed to wrap the cell ref in 3 lots of ". So now its:
QUERY(nameGen!$A$1:$G500, "SELECT D WHERE B matches """&$B1091&"""",0)

An alternate option is to use;
"string 1"&char(34)&"string2".
Edit; looks like Google sheets uses char(39) - mssql uses char(39) to quote strings, Excel / vba uses char(34).
For other special characters if applicable check an ASCII table...

Related

SQL finding rows that only contain chars from a certain Unicode range

I recently asked a question to obtain rows that contain characters in a certain Unicode range.
SELECT *
FROM #kanjinames
WHERE UNICODE(LEFT(ForeNames, 1)) BETWEEN 0x4e00 AND 0x9fff
A very helpful user shared the above with me. To my understanding it checks the first character on the left and if it is within the Unicode range it returns an a the row. Through testing I believe this works.
My current problem is how do I go about checking the entire column is within the range? For example:
石山コンタクトレンズ
The above contains characters outside of the range (the first two characters are within range) in the query above but I am not sure about how I go about checking the entire field. I am away of using stuff like
is not like N'%^a-z%'
for the English alphabet. Just not sure how to apply it for this situation.
Any help would be great on this.
I think this will work:
SELECT *
FROM #kanjinames
WHERE ForeNames NOT LIKE '%[^' + NCHAR(0x4e00) + '-' NCHAR(0x9fff) + ']%';
That is, the string contains no characters outside that sequence.
Edit: I had to alter this slightly to get it to work. I had to use the decimal values instead of the hex.
SELECT *
FROM #kanjinames
WHERE ForeNames NOT LIKE '%[^' + NCHAR(19968) + '-' + NCHAR(40802) + ']%';
This still returns blank values but I removed those separately.

Search string with regular expression SQL Server

The regex I want to use is: ^(?=.*[,])(,?)ABC(,?)$
What I want to get out is:
^ // start
(?=.*[,]) // contains at least one comma (,)
(,?)ABC(,?) // The comma is either in the beginning or in the end of the string "ABC"
$ // end
Of course ABC is ought to be a variable based on my search term.
So if ABC = 'abc' then ",abc", "abc,", ",abc," will match but not "abc" or "abcd"
Better way to do this is also welcome.
The value in the record looks like "abc,def,ghi,ab,cde..." and I need to find out if it contains my element (i.e. 'abc'). I cannot change the data structure. We can assume that in no case the record will contain only one sub-value, so it is correct to assume that there always is a comma in the value.
If you want to know if a comma delimited string contains abc, then I think like is the easiest method in any database:
where ',' + col + ',' like '%,abc,%'

how do I retrieve data from a sql table with huge number of inputs for a single column

I have a Company table in SQL Server and I would like to retrieve list of data related to particular companies and list of companies is very huge of around 200 company names and I am trying to use IN clause of T-SQL which is complicating the retrieval as few the companies have special characters in their name like O'Brien and so its throwing up an error as it is obvious.
SELECT *
FROM COMPANY
WHERE COMPANYNAME IN
('Archer Daniels Midland'
'Shell Trading (US) Company - Financial'
'Redwood Fund, LLC'
'Bunge Global Agribusiness - Matt Thibodeaux'
'PTG, LLC'
'Morgan Stanley Capital Group'
'Vitol Inc.'..
.....
....
.....)
Above is the script that is not working for obvious reasons, is there any way I can input those company names from an excel file and retrieve the data?
The easiest way would be to make a table and join it:
CREATE TABLE dbo.IncludedCompanies (CompanyName varchar(1000)
INSERT INTO dbo.IncludedCompanies
VALUES
('Archer Daniels Midland'),
('PTG, LLC')
...
SELECT *
FROM Company C
JOIN IncludedCompanies IC
ON C.CompanyName = IC.CompanyName
I do not think that mysql knows how to handle excel format, but you can fix your query.
Check how complicated names are stored in database (check if they have escape characters in them or anything else".
Replace all ' with \' in your query and it will take care of the ' characters
mysql> select now() as 'O\'Brian'; returns
O'Brian
2014-03-17 15:06:39
So i'm guessing you have a excel sheet with a column containing these names, and you want to use this in your where clause. In addition, some of the values have special characters in them, which needs to be escaped.
First thing you do is to escape the '-characters. You do this in excel, with a search replace for all occurences of ' with '' (the escaped version in sqlserver (\' in MySQL.)) Then, create a new column on each side side of your companies column, and in the first row input a ' on the left hand side, and ', on the right. Then use the copy cell functionality (the little square in the bottom right of the cell when you select it) to copy the cells to the left and right to all the rows, as far as the company list goes (just grab the square and pull it downwards..)
Then, take your list, now containing three columns and x rows and paste it into your favorite text editor. It should look something like this:
' Company#1 ',
' Company with special '' char ',
[...]
' Last company ',
Now, you will have some whitespace to get rid of. Use search replace and replace two space characters with nothing, and repeat (or take the space from the first ' to the start of the text and replace this with nothing.
Now, you should have a list of:
'Company#1',
'Company with special '' char',
[...]
'Last company',
Remove the last comma, and you'll have a valid list of parameters to your in-clause (or a (temporary) table if you want to keep your query a bit cleaner.)

Replace quote in SQL Select

I have a scenario in my vb.net project where users need to select a name from a combobox (or type a new name).
Names of course can have ' as in Tina O'Hara which in the database would be stored as Tina O''Hara.
My combobox is populated from a sql select command. I have tried to use a Replace so that the names display correctly in the dropdown.
SqlStr = "SELECT Replace(ContactName, '''', ''') AS ddlText FROM tbl_Visits Where CustID = " & hd_CustID.value & " ORDER By ContactName"
PopulateCMBX(cmbx_ContactName, SqlStr, "Please Select")
PopulateCMBX... This gets a list of names from the supplied SqlStr and populates the combobox itemlist with a 'Please Select' as the first option.
SqlStr is producing an error as there is not a matching set of ' how do I fix this. Thanks
When referencing single quotes in MS-SQL, you need to escape each single quote (') with two single quotes ('').
If the name is stored in the database with two single quotes, such as (''), then when you do the replace you need to use four single quotes (''''). In addition to these, you need to enclose the string with single quotes.
What this means is that your replace should look like this:
SqlStr = "SELECT Replace(ContactName, '''''', '''') ...
The 2nd param in the replace has 6 single quotes: 4 to represent the two single quotes you are replacing, and 2 to make it a string. The 3rd param has 4 single quotes: 2 to represent a single escaped quote and two to make it a string.
Try with this, maybe not the best solution but it works (check this example):
select Replace(Replace(ContactName, '''', '$&'),'$&$&','''') from tbl_Visits
Note that $& is like a key that should not affect the values ​​in your field, for example, could be a word: &&k&& or %%key%%, etc.
Back to clarify, it is not the best solution, but sometimes i've used.

How to replace common words in sql column

I have a table of common words that are used in sentences (i.e. A, the, and, where, etc...)
What I want to do is loop through all those words and strip them out of the descriptions that people have entered to attempt to generate common keywords or tags. But I can't use replace because replace will remove any instance of the common word regardless of whether it is only a couple of letters that make up a larger word. For instance:
I want to replace A in the description. Now obviously a lot of words contain the letter a. So all those A's will be stripped from the words. I don't want that. I only want it when A is used a a whole word. I can figure this out using regular expressions but was wondering if there was anyway to do this in SQL without having to resort to CLR proc.
Maybe I am missing something but I couldn't seem to find an easy way to do this without having to write some specific scenarios like: word plus space before, word plus space after, word plus period after, etc... I don't think that is the best way.
For quick and dirty, I used to slosh through the various SQL functions PATINDEX, LEFT, RIGHT and LIKE to do this sort of thing. For one-time data prep, I export to something like Excel and eyeball it.
A good approach also is to create a new StringSubstitutionTable with two columns SOURCESTRING and TARGETSTRING and run a replace function to replace the SOURCESTRING with the TARGETSTRING on the joined table. This is cool because you can just add substitution entries as needed.
You can try nesting the replaces for each word you would like to replace. For example:
UPDATE TableName
SET ColumnName = REPLACE(REPLACE(REPLACE(REPLACE(TableName.ColumnName,' a ',' '),' the ',' '),' and ',' '), ' ', ' ')
Let me know if this is what you were looking for.
Here is they way I did something similar to what you are trying to do.
During your replace action...
Append a space before and after the common word.
Append a space before and after the description.
Let's suppose you want to remove the CommonWord "A" from the Description.
Description: "A good phrase never starts with A or ends with A"
CommonWord: "A"
Update TableName
Set Description =
LTRIM(RTRIM(Replace(' ' + Description + ' ', ' ' + CommonWord + ' ', ' ')))
This lets you delete all whole words that equal 'A'. Because you are replacing ' A ' with a space you need to LTRIM RTRIM to remove any leading or trailing spaces.
You could also do this in two steps:
--
-- Step 1 Loop through all common words removing them
--
Update TableName
Set Description = Replace(' ' + Description + ' ', ' ' + CommonWord + ' ', ' ')
--
-- Step 2 Unconditionally Trim all Descriptions
--
Update TableName
Set Description = LTRIM(RTIM(Description))