SQL Server statement Where myfield content giving sub-string - sql

I'm looking for a SQL Server statement to retrieve records Where myfield content giving sub-string.

Another possibility is to use LIKE:
SELECT
MT.column_1,
....
FROM
My_Table MT
WHERE
some_column LIKE '%' + #search_string + '%'

You can use CharIndex
Select * From YourTable
Where
CharIndex('yoursubstring', myfield) > 0

Try PatIndex.
SELECT *
FROM Table
WHERE patindex('%string%', data ) > 0

select * from mytable where myfield like '%literalstring%'
or
select * from mytable where myfield like '%' + #stringvar + '%'
...not really clear on whether your substring is a literal or a variable

Related

How can I use contains to look for keyword including a space?

I want to use contains with search a word that has single space on left and right side. But it is not working..
SELECT *
FROM mytable
WHERE Contains(name, ' Hertz ');
Any help is appreciated..
You Can LTRIM RTRIM the column and can get the values.
create table #temp
(
name varchar(50)
)
insert into #temp values(' hertz')
insert into #temp values('hertz ')
insert into #temp values('hertzx')
insert into #temp values('hertz')
select * from #temp where LTRIM(RTRIM(name)) like '%hertz%'
If you want to search if it has space in start or end use below query.
select * from #temp where name like ' %'
select * from #temp where name like '% '
Try with this:
SELECT *
FROM mytable
WHERE name=' Hertz '
If Hertz is just an example, you can use:
SELECT *
FROM mytable
WHERE name like ' % '
which will return all the names with an space in the first and last position
Try as below.
SELECT *
FROM mytable
WHERE name LIKE '% Hertz %'
Learn more about like operator
You could try this
SELECT *
FROM mytable
WHERE name Like '% Hertz %'
To search with spaces included, you need to enclose your expression within double quotes, like :
SELECT *
FROM mytable
WHERE CONTAINS(name, '" Hertz "');
Of course this also can be written with LIKE (although it will be less efficient when dealing with large data sets) :
SELECT *
FROM mytable
WHERE name LIKE '% Hertz %');
If you use like operator, you no need to give spaces between that like below
select * from mytable where name like '%her%'
And also if you want the data of which having spaces, you can use like below
select * from mytable where name like '_%hertz%_'
If we use underscore, it will skip the particular position element and search the data.
Try this
Select * from mytable where replace(name,' ','')='Hertz'
You can also use ltrim & rtrim to remove spaces at run time to match the name values.
You can try this
SELECT a.name
FROM mytable a
WHERE a.name like ' %% '
OR
SELECT a.name
FROM mytable a
WHERE a.name like' % '
You can find the live demo Demo here

SQL Select Statement LIKE IN

I need to write a select statement which returns a list of users where a list of SenderSubIDs exist in a field called constraint_values:
I need a LIKE IN statement ideally:
SELECT SenderSubID FROM fix_user_subids WHERE SenderSubID IN ('**00390529MGERAN1**','**00912220PBALDIS**','**03994113LDAMBRO**','**04004308SLOMBAR**','**04935278CARELLI**','**4004308SLOMBARD**')
SELECT * FROM fix_dyno_rule_defs WHERE constraint_values LIKE '%**00390529MGERAN1**%'
Returns:
rule_def_id tag msg_type required constraint_values constraint_type data_type default_value validation_type trans_type attribute_tag trans_tag memo
99800 10000 D,F,G 0 ((50,4,1,00390529MGERAN1)or(50,4,1,00912220PBALDIS)or(50,4,1,03994113LDAMBRO)or(50,4,1,04004308SLOMBAR)or(50,4,1,04935278CARELLI)or(50,4,1,4004308SLOMBARD))and(21,4,1,3)#STROP1#addattr(EQD,EQST) 0 1 #TAG=6506# 12 1800 0 0 Set EQD=1 for Equity Desk
I wrote this:
SELECT * FROM fix_dyno_rule_defs WHERE constraint_values LIKE '%' + (SELECT MAX(SenderSubID) FROM fix_user_subids WHERE SenderSubID IN ('00390529MGERAN1','00912220PBALDIS','03994113LDAMBRO','04004308SLOMBAR','04935278CARELLI','4004308SLOMBARD')) +'%'
But need it without the MAX as there is a list...
You don't get your ideal. Use or:
SELECT SenderSubID
FROM fix_user_subid
WHERE SenderSubID like '%00390529MGERAN1%' OR
SenderSubID like '%00912220PBALDIS%' OR
SenderSubID like '%04004308SLOMBAR%' OR
SenderSubID like '%04935278CARELLI%' OR
SenderSubID like '%4004308SLOMBARD%'
/This should help you try this
declare a temp table and store all the IDs in it/
declare #tempSenderIDs Table(
T_TableID varchar(10)
)
insert into #tempSender
(
T_TableID
)
values
select
senderSubID
from
SenderSubIDs
/final result will come from here/
select
f.SenderSubIDs
from
fix_user_subid f
where
s.ConstraintValue like '%' + (select T_TableID from #tempSenderIDs) +'%'
If I'm reading your question right (and I might not be!) you're looking to get results from the table fix_dyno_rule_defs.
In which case, can't you just do a simple join?
ie:
SELECT DISTINCT fdrd.*
FROM fix_dyno_rule_defs fdrd
JOIN fix_user_subid fus
ON fdrd.constraint_values LIKE '%' + REPLACE(fus.SenderSubID, '*','') + '%'
WHERE fus.SenderSubID IN ('**00390529MGERAN1**','**00912220PBALDIS**',
'**03994113LDAMBRO**','**04004308SLOMBAR**',
'**04935278CARELLI**','**4004308SLOMBARD**')

Comparing value with comma separated values in select statement

this is how my table looks like :
Now i want to retrieve Field1 for 'AAA'
I tried something like :
select Field1 from table where CommaSeparatedList='AAA'
But it didn't work.
So How can I achieve this ??
select field1
from table
where ',' + replace(commaseparatedlist, ' ', '') + ',' like '%,AAA,%'
I suggest that you try:
SELECT Field1 FROM table WHERE CommaSeparatedList LIKE '%AAA%'
If you just need the column to contain the value you are looking for, you could do something like this:
SELECT Field1
FROM table
WHERE CommaSeparatedList LIKE '%AAA%'

How to pass parameter to stored procedure

I am using SQL Server 2008 Enterprise on Windows Server 2008 Enterprise. In the stored procedure, I need to pass parameter to a select-where-like statement. For example,
#department is store procedure input parameter, its type is varchar(20),
select * from sometable where somecolumn LIKE '%#department%'
but seems my statement above does not work, any ideas how to pass parameter #department to like statement?
thanks in advance,
George
select * /*But don't use * in production!*/
from sometable
where somecolumn
LIKE '%' + #department + '%'
You concatenate the strings:
select * from sometable where somecolumn LIKE '%' + #department + '%'
It's a variable, it goes outside the quotes.
select * from sometable where somecol like '%' + #department + '%'
Or, more preferably, add the %s to the variable and just use it directly
try:
select * from sometable where somecolumn LIKE '%' + #department + '%'
You could do something like this:
select * from sometable where somecolumn LIKE '%' + #department + '%'
select * from sometable
where CHARINDEX(#department,somecolumn)>0
You can also use the CHARINDEX function.

SQL Server 2008: How to find trailing spaces

How can I find all column values in a column which have trailing spaces? For leading spaces it would simply be
select col from table where substring(col,1,1) = ' ';
You can find trailing spaces with LIKE:
SELECT col FROM tbl WHERE col LIKE '% '
SQL Server 2005:
select col from tbl where right(col, 1) = ' '
As a demo:
select
case when right('said Fred', 1) = ' ' then 1 else 0 end as NoTrail,
case when right('said Fred ', 1) = ' ' then 1 else 0 end as WithTrail
returns
NoTrail WithTrail
0 1
This is what worked for me:
select * from table_name where column_name not like RTRIM(column_name)
This will give you all the records that have trailing spaces.
If you want to get the records that have either leading or trailing spaces then you could use this:
select * from table_name where column_name not like LTRIM(RTRIM(column_name))
A very simple method is to use the LEN function.
LEN will trim trailing spaces but not preceeding spaces, so if your LEN() is different from your LEN(REVERSE()) you'll get all rows with trailing spaces:
select col from table where LEN(col) <> LEN(REVERSE(col));
this can also be used to figure out how many spaces you have for more advanced logic.
SELECT * FROM tbl WHERE LEN(col) != DATALENGTH(col)
Should work also.
There's a few different ways to do this...
My favorite option, assuming your intention is to remove any leading and / or trailing spaces, is to execute the following, which will dynamically create the T-SQL to UPDATE all columns with an unwanted space to their trimmed value:
SELECT
'UPDATE [<DatabaseName>].[dbo].['+TABLE_NAME+']
SET ['+COLUMN_NAME+']=LTRIM(RTRIM(['+COLUMN_NAME+']))
WHERE ['+COLUMN_NAME+']=LTRIM(RTRIM(['+COLUMN_NAME+']));'+CHAR(13)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME LIKE '<TableName>%'
AND DATA_TYPE!='date'
ORDER BY TABLE_NAME,COLUMN_NAME
If you really need to identify them though, try one of these queries:
SELECT *
FROM [database].[schema].[table]
WHERE [col1]!=LTRIM(RTRIM([col1]))
More dynamic SQL:
SELECT 'SELECT ''['+TABLE_NAME+'].['+COLUMN_NAME+']'',*
FROM [<your database name>].[dbo].['+TABLE_NAME+']
WHERE ['+COLUMN_NAME+'] LIKE ''% ''
OR ['+COLUMN_NAME+'] LIKE '' %'';
GO
'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME LIKE '<filter table name as desired>%'
AND DATA_TYPE!='date'
Here's an alternative to find records with leading or trailing whitespace, including tabs etc:
SELECT * FROM tbl WHERE NOT TRIM(col) = col
Try this:
UPDATE Battles
SET name = CASE WHEN (LEN(name+'a')-1)>LEN(RTRIM(name))
THEN REPLICATE(' ', (LEN(name+'a')-1)- LEN(RTRIM(name)))+RTRIM(name)
ELSE name
END
Spaces are ignored in SQL Server so for me even the leading space was not working .
select col from table where substring(col,1,1) = ' '
wont work if there is only one space (' ') or blank ('')
so I devised following:
select * from [table] where substring(REPLACE(col, ' ', '#'),1,1) = '#'
Here is another alternative for trailing spaces.
DECLARE #VALUE VARCHAR(50) = NULL
DECLARE #VALUE VARCHAR(50) = ' '
IF ((#VALUE IS NOT NULL) AND (LTRIM(RTRIM(#VALUE)) != ''))
BEGIN
SELECT 'TRUE'
END
ELSE
BEGIN
SELECT 'FALSE'
END
I have found the accepted answer a little bit slower:
SELECT col FROM tbl WHERE col LIKE '% ';
against this technique:
SELECT col FROM tbl WHERE ASCII(RIGHT([value], 1)) = 32;
The idea is to get the last char, but compare its ASCII code with the ASCII code of space instead only with ' ' (space). If we use only ' ' space, an empty string will yield true:
DECLARE #EmptyString NVARCHAR(12) = '';
SELECT IIF(RIGHT(#EmptyString, 1) = ' ', 1, 0); -- this returns 1
The above is because of the Microsoft's implementation of string comparisons.
So, how fast exactly?
You can try the following code:
CREATE TABLE #DataSource
(
[RowID] INT PRIMARY KEY IDENTITY(1,1)
,[value] NVARCHAR(1024)
);
INSERT INTO #DataSource ([value])
SELECT TOP (1000000) 'text ' + CAST(ROW_NUMBER() OVER(ORDER BY t1.number) AS VARCHAR(12))
FROM master..spt_values t1
CROSS JOIN master..spt_values t2
UPDATE #DataSource
SET [value] = [value] + ' '
WHERE [RowID] = 100000;
SELECT *
FROM #DataSource
WHERE ASCII(RIGHT([value], 1)) = 32;
SELECT *
FROM #DataSource
WHERE [value] LIKE '% ';
On my machine there is around 1 second difference:
I have test it on table with 600k rows, but larger size, and the difference was above 8 seconds. So, how fast exactly will depend on your real case data.
Another way to achieve this by using CHARINDEX and REVERSE like below:
select col1 from table1
WHERE charindex(' ', reverse(col1)) = 1
See example Here
Simple use below query to get values having any number of spaces in begining or at end of values in column.
select * from table_name where column_name like ' %' or column_name like '% ';
We can try underscore to find the entries which are blanks,though not an accurate solution like using '% %' or ' ', But I could find entries which are blanks.
select col_name from table where col_name like '_'