SQL select statement - sql

in a string array i have a variable amount of values.
how will an sql statement look if i want to select all the records that are equal with the array variables.
it will look something this:
SELECT * FROM users WHERE username='"+ variable amount of elements in the String array like: Steven, Mike, John ..... +"'"

You might be looking for the IN( ) operator.
SELECT * FROM users WHERE username IN ('chris', 'bob', 'bill');

This? (obviously the "OR username='xxx' is repeated for as many items as you require)
SELECT * FROM users WHERE username='item1' OR username='item2' OR username='item3'

Every one above me is corrrect! There are multiple ways of doing this! A simple google search for 'mysql statement variables' yield tons of help full results including:
http://www.daniweb.com/forums/thread126895.html
Just treat your array like a standard varible with [a number] on the end!
Two tips come from this:
Google / Search your problem first 9 times out of 10 someone else has had the same problem and found a working solution!
And be prepared to look at the answers on here with in 5 mins. This forums probably the quickest you'll ever see. The only thing that slows the community down is typing ! :P
Hope that Helps,
Andy

Another approach, although less efficient, can be used if parsing the string apart is problematic...
DECLARE #listOfNames VARCHAR(2000)
SET #ListOfNames = 'JOE,KELLIE,PETE'
SELECT * FROM users WHERE charindex(","+userName+",",","+#listOfNames+",") > 0
This approach is slower than either of the other answers, but can save you from using dynamic SQL to build a SQL query based on the list of names passed in...

Related

Clickhouse, column values to array

I want to make a query then turn the values for each of it's columns into arrays, I've tried finding a way to do this, but until now it has alluded me.
The query is a simple select:
SELECT a,b,c FROM X
Instead of the usual result of say (in the default format):
val_a_1, val_b_1, val_c_1
----------------
val_a_2, val_b_2, val_c_2
-----------------
val_a_3, val_b_3, val_c_3
I want to get an array for each columns, namely:
[val_a_1, val_a_2, val_a_3], [val_b_1, val_b_2, val_b_3] , [val_c_1, val_c_2, val_c_3]
Is this at all possible ?
Nevermind, this can easily be done with groupArray as:
SELECT groupArray(a), groupArray(b), groupArray(c) FROM X
It completely slipped my mind and google didn't help...
leaving this here in case there's a better option or anyone stumbles upon it when searching.

SQL Like filtering

Welcome!
I am currently working on some C# and I encountered a rather silly issue. I need to fill ListBox with some data from database obviously. Problem is varchar filtering. I need to filter codes and display only the right ones.
Example of codes are: RRTT, RRTR, RT12, RQ00, R100, R200, R355, TY44, GG77 etc. Four digit codes.
I managed to filter only R-codes with simple select * from table1 where code_field like 'R%' but I get both R000 and RQ10 and I need to get R ones followed by numbers only.
So from example:
RRTT, RRTR, RT12, RQ00, R100, R200, R355
Only:
R100, R200, R355
Any ideas what should I add to the like 'R%'?
In SQL Server, you can make use of wildcards. Here is one approach:
where rcode like 'R___' and -- make sure code has four characters
rcode not like 'R%[^0-9]%' -- and nothing after the first one is not a number
Or:
where rcode like 'R[0-9][0-9][0-9]'
In other databases, you would normally do this using regular expressions rather than extensions to like.
here solution using like
SELECT *
FROM (
VALUES ( 'R123'),
( 'R12T' ),
( 'RT12' )
) AS t(test)
where test like 'R[0-9][0-9][0-9]'
like 'S[0-9%]'
Friend came up with the solution, thanks anyway

How to Filter WHERE Field Value LIKE any of the values stored in a Multi Value Parameter in SQL

I have a report (built using SSRS) that uses a multi-value parameter.
I want to add a Filter onto my SQL Query WHERE FieldA is LIKE any of the values stored in the parameter.
So FieldA might have the following values:
BOBJAMESLOUISE
MARYBOB
JENNY
JOHNLOUISEJAMES
BOB
JENNYJAMESMIKE
And #ParamA might have the following values:
Bob, Louise
Therefore in this example only records 1, 3, 4 and 5 should be returned
Thanks to any help in advance :)
P.S I'm using SQL Server 2008
You will want to implement a function like the split function. This can take a comma separated value list and separate it into rows like you want.
Below is a link for a couple of different versions, any of them will work for you. It also tells you how to use it.
Split Function
I am guessing its not the spiting sting part that is the issue since just googling for SQL split string you can find a lot of example. In your case what you would want after the split string is something like this. Assuming that the split string function you end up using returns a table of values Here is what your comparison query for with field A would look like.
SELECT * FROM YourTableWithFieldA WHERE (#ParamA IS NULL OR EXISTS ( SELECT * FROM YourSplitFunctionThatReturnsATableOfValues(#ParamA) SplitTable WHERE (FieldA Like '%'+SplitTable.Value+'%')))

Find exact match using full-text search

Using the Sql Server 2008 how can you actually find an exact string match using full-text search. I'm having a real hard time with this and I just couldn't find a satisfactory solution anywhere online.
For example, if I'm searching for the string "Bojan Skrchevski" I want the first result to be exactly that.
So far I've tried formatting the string like: "Bojan* NEAR Skrchevski*" and call CONTAINSTABLE to get results, but this string is formatted to return more results as Bojana and Bojananana etc. I also tried to ORDER BY RANK, but still no success.
Furthermore, in my string I have a number sequence like: "3 1 7", but with the current formatting it also returns "7 1 3" etc.
Example:
DECLARE #var varchar(4000);
SET #var = '"Oxford*" NEAR 24 NEAR 7 NEAR 5 NEAR "London*"'
SELECT [Key] FROM CONTAINSTABLE(dbo.[MyTable], [MyField], #var);
I want to be able to get the exact ordering. Not to get "Oxford 7 24 5 London" as a result.
How do I format the string to accomplish this correctly?
There's 2 options
1)
This will get all items which have Mountain in their name
SELECT Name, ListPrice
FROM Production.Product
WHERE ListPrice = 80.99
AND CONTAINS(Name, 'Mountain');
GO
2)
This will get all items which have these 3 strings in Document no matter what order
SELECT Title
FROM Production.Document
WHERE FREETEXT (Document, 'vital safety components' );
It depends on what you really want but I couldn't understand completely.
If I'm missing the point please post a sample and what the result should be.
kr,
Kristof
Perhaps one approach could be to select several results with the full-text search and then SELECT the specific one from those results. But maybe there could be a better solution to this.
I tried this approach and it actually worked. It also works a lot faster then to just SELECT the value.

SQL produced by Entity Framework for string matching

Given this linq query against an EF data context:
var customers = data.Customers.Where(c => c.EmailDomain.StartsWith(term))
You’d expect it to produce SQL like this, right?
SELECT {cols} FROM Customers WHERE EmailDomain LIKE #term+’%’
Well, actually, it does something like this:
SELECT {cols} FROM Customer WHERE ((CAST(CHARINDEX(#term, EmailDomain) AS int)) = 1)
Do you know why?
Also, replacing the Where selector to:
c => c.EmailDomain.Substring(0, term.Length) == term
it runs 10 times faster but still produces some pretty yucky SQL.
NOTE: Linq to SQL correctly translates StartsWith into Like {term}%, and nHibernate has a dedicated LikeExpression.
I don't know about MS SQL server but on SQL server compact LIKE 'foo%' is thousands time faster than CHARINDEX, if you have INDEX on seach column. And now I'm sitting and pulling my hair out how to force it use LIKE.
http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/1b835b94-7259-4284-a2a6-3d5ebda76e4b
The reason is that CharIndex is a lot faster and cleaner for SQL to perform than LIKE. The reason is, that you can have some crazy "LIKE" clauses. Example:
SELECT * FROM Customer WHERE EmailDomain LIKE 'abc%de%sss%'
But, the "CHARINDEX" function (which is basically "IndexOf") ONLY handles finding the first instance of a set of characters... no wildcards are allowed.
So, there's your answer :)
EDIT: I just wanted to add that I encourage people to use CHARINDEX in their SQL queries for things that they didn't need "LIKE" for. It is important to note though that in SQL Server 2000... a "Text" field can use the LIKE method, but not CHARINDEX.
Performance seems to be about equal between LIKE and CHARINDEX, so that should not be the reason. See here or here for some discussion. Also the CAST is very weird because CHARINDEX returns an int.
charindex returns the location of the first term within the second term.
sql starts with 1 as the first location (0 = not found)
http://msdn.microsoft.com/en-us/library/ms186323.aspx
i don't know why it uses that syntax but that's how it works
I agree that it is no faster, I was retrieving tens of thousands of rows from our database with the letter i the name. I did find however that you need to use > rather than = ... so use
{cols} FROM Customer WHERE ((CAST(CHARINDEX(#term, EmailDomain) AS int)) > 0)
rather than
{cols} FROM Customer WHERE ((CAST(CHARINDEX(#term, EmailDomain) AS int)) = 1)
Here are my two tests ....
select * from members where surname like '%i%' --12 seconds
select * from sc4_persons where ((CAST(CHARINDEX('i', surname) AS int)) > 0) --12 seconds
select * from sc4_persons where ((CAST(CHARINDEX('i', surname) AS int)) = 1) --too few results