How to find fields containing the TAB character in SQL Server - sql-server

In SQL Server, what is the best way to identify all rows in a table where a certain column contains the TAB character (CHAR(9))
Is it as simple as
SELECT * FROM MyTable WHERE Field1 LIKE '%' + CHAR(9) + '%'

RTRIM CHAR columns. like this:
SELECT *
FROM MyTable
WHERE (RTRIM(Field1) LIKE '%' + CHAR(9) + '%')

Previous query fails, with: "missing expression" message,
In Oracle, this is the correct syntax
select *
from MyTable
where Field1 '%' || CHR(9) || '%';
Other solution can be:
Select *
from MyTable
where instr(Field1, CHR(9)) <> 0;
Cheers!

Related

Compare String values in SQL

I have a stored procedure which is called from a program. This stored procedure is passed 2 names and needs to find similar names in the database. However when I try to compare - 'AFC Bournemouth' with the name in the db which is 'Bournemouth'.
bet.searchFixtureForResult
#homeTeam NVARCHAR(MAX),
#awayTeam NVARCHAR(MAX),
#date DATE
AS
SELECT fixtureId
FROM bet.fixture
WHERE homeTeam IN (SELECT teamId
FROM bet.team
WHERE team LIKE '%' + #homeTeam + '%')
AND awayTeam IN (SELECT teamId
FROM bet.team
WHERE team LIKE '%' + #awayTeam + '%')
AND fixtureDate = #date
This supposedly returns the Id of the fixture that falls within the parameters given. How can compare similar strings such that I compare in the same way you compare with .Contains in C#?
I don't think you need bet.team there at all, your query will be like
SELECT fixtureId
FROM bet.fixture
WHERE (HomeTeam LIKE '%' + #HomeTeam + '%' OR #HomeTeam LIKE '%' + HomeTeam + '%')
AND
(AwayTeam LIKE '%' + #AwayTeam + '%' OR #AwayTeam LIKE '%' + AwayTeam + '%')
AND
fixtureDate = #date;
Here is a little Demo

Look for specific special characters SQL Server 2008 R2

I need to look for mention of below special characters in a description field string/rows. Some of these are straightforward, but there are some I can't figure out how to look for:
Special characters: < > { } [ ] " ' * = # ~ | <Tab> (tab key) <Enter> (extra line (carriage return))
what I have so far:
select * from
table
where [Account description] like '[<>{}[]*=#~|]'
Not sure how to identify following special characters:
" (double quote)
' (single quote)
<Tab> (tab key)
<Enter> (extra line (carriage return))
Sounds like you want all non-alphanumeric characters? if so, you can use
declare #table table (id int identity (1,1), column1 nvarchar(64))
insert into #table
values
('<'),
('>'),
('{'),
('}'),
('['),
(']'),
('"'),
(''''),
('*'),
('='),
('#'),
('~'),
('|'),
('a' + char(10)),
('b' + char(13)),
('c' + char(9)),
('a'),
('A'),
('1')
select *
from #table
where [Account description] like '%[^0-9a-zA-Z]%'
Otherwise, you'll need to list them explicit and use an escape value for the special cases...
select *
from #table
where column1 like '%[<>{}![!]"''''*=#~|]%' ESCAPE '!'
or column1 like '%' + char(10) + '%'
or column1 like '%' + char(9) + '%'
or column1 like '%' + char(13) + '%'
May be you could try something like this:
select * from table
where [Account description] like '[<>{}[]*=#~|]'
and [Account description] like '%''%'
and [Account description] like '%'+CAST(X'09' AS TEXT)+'%'
and ([Account description] like '%'+char(13)+'%'
or [Account description] like '%'+char(10)+'%)
but I think is gonna be slow.

Search Varchar and Integer Columns in T-SQL

I have a search functionality in my application which searches a string value of a particular column. The search text is passed as a parameter to the procedure. Now I have to search in another column which is an integer from another table. The input param is one but now I have to search in both the columns and return the result according to that.
//Query:
#SearchText VARCHAR(8000) = ''
SELECT DISTINCT Id, TransactionId, wfdFieldValue
where (wfdFieldValue LIKE '%' + #SearchText + '%' OR #SearchText = '')
In the above query I have to include the TransactionId in the where condition. So that if the user searched using the TransactionId or the Fieldvalue the query will return the result.
Note: The TransactionId is an Integer DataType.
If I understand you correctly, you'll want a hit in either column to make the row show up in search results. In that case, you'll need a simple OR;
SELECT DISTINCT Id, TransactionId, wfdFieldValue
FROM bop
WHERE #SearchText='' OR
wfdFieldValue LIKE '%' + #SearchText + '%' OR
TransactionId LIKE '%' + #SearchText + '%'
(You can just use LIKE on the integer column right away without manually converting.)
Of note though, this kind of wildcard search with a leading % does not use indexes in an optimal way, performance of this query will most likely not be great as the table grows.
SELECT DISTINCT Id, TransactionId, wfdFieldValue
where wfdFieldValue LIKE '%' + #SearchText + '%'
OR #SearchText = ''
OR CAST(TransactionId AS VARCHAR(50)) LIKE '%' + #SearchText + '%'
A cast should solve it, but I would first think about possible design improvements.

SQL Server WHERE with wildcard

Is it possible to use a wildcard for the where in statement in SQL Server 2008?
For example, I currently have:
SELECT something
FROM myTable
WHERE (ORG + '-' + ORGSUB like '5015001-________' or
ORG + '-' + ORGSUB like '5015018-________' or
ORG + '-' + ORGSUB like '_______-________')
I need to do it this way:
SELECT something
FROM myTable
WHERE
(ORG + '-' + ORGSUB) in( '5015001-________','5015018-________','_______-________')
i'm going to be passing those values through a stored procedure as a comma delimited list. is there another way to get it done?
Take your comma delimited list, split it, and insert it into a temp table...
You can then use a LIKE statement in a JOIN to this temp table:
SELECT something
FROM myTable mt
JOIN #tempTable tt
ON mt.ORG + '-' + mt.ORGSUB LIKE tt.SearchValue
Why do you even care about ORGSUB in your query (as provided in the example)?
Seems to me you should rewrite your WHERE clause to look for the components separately, e.g.:
SELECT something
FROM myTable
WHERE ORG IN (5015001, 5015018, ...)
[add other criteria as appropriate]
Why a comma-separated list?
DECLARE TYPE dbo.OrgSub AS TABLE(s VARCHAR(32));
GO
CREATE PROCEDURE dbo.SearchOrgSubs
#OrgSub dbo.OrgSub READONLY
AS
BEGIN
SET NOCOUNT ON;
SELECT t.something
FROM dbo.mytable AS t
INNER JOIN #OrgSub AS o
ON t.ORG + '-' + t.ORGSUB = o.s;
END
GO
Now you can pass the set into the stored procedure from C# or wherever, without first having to form it into a comma-separated list.
You can create a temp Table contains the result of a split function.
SELECT somthing
from myTable
JOIN dbo.Split('5015001-________','5015018-________','_______-________') as Splits
on (ORG + '-' + ORGSUB) like Splits.items

How to convert empty spaces into null values, using SQL Server?

I have a table and the columns on this table contains empty spaces for some records. Now I need to move the data to another table and replace the empty spaces with a NULL value.
I tried to use:
REPLACE(ltrim(rtrim(col1)),' ',NULL)
but it doesn't work. It will convert all of the values of col1 to NULL. I just want to convert only those values that have empty spaces to NULL.
I solved a similar problem using NULLIF function:
UPDATE table
SET col1 = NULLIF(col1, '')
From the T-SQL reference:
NULLIF returns the first expression if the two expressions are not equal. If the expressions are equal, NULLIF returns a null value of the type of the first expression.
Did you try this?
UPDATE table
SET col1 = NULL
WHERE col1 = ''
As the commenters point out, you don't have to do ltrim() or rtrim(), and NULL columns will not match ''.
SQL Server ignores trailing whitespace when comparing strings, so ' ' = ''. Just use the following query for your update
UPDATE table
SET col1 = NULL
WHERE col1 = ''
NULL values in your table will stay NULL, and col1s with any number on space only characters will be changed to NULL.
If you want to do it during your copy from one table to another, use this:
INSERT INTO newtable ( col1, othercolumn )
SELECT
NULLIF(col1, ''),
othercolumn
FROM table
This code generates some SQL which can achieve this on every table and column in the database:
SELECT
'UPDATE ['+T.TABLE_SCHEMA+'].[' + T.TABLE_NAME + '] SET [' + COLUMN_NAME + '] = NULL
WHERE [' + COLUMN_NAME + '] = '''''
FROM
INFORMATION_SCHEMA.columns C
INNER JOIN
INFORMATION_SCHEMA.TABLES T ON C.TABLE_NAME=T.TABLE_NAME AND C.TABLE_SCHEMA=T.TABLE_SCHEMA
WHERE
DATA_TYPE IN ('char','nchar','varchar','nvarchar')
AND C.IS_NULLABLE='YES'
AND T.TABLE_TYPE='BASE TABLE'
A case statement should do the trick when selecting from your source table:
CASE
WHEN col1 = ' ' THEN NULL
ELSE col1
END col1
Also, one thing to note is that your LTRIM and RTRIM reduce the value from a space (' ') to blank (''). If you need to remove white space, then the case statement should be modified appropriately:
CASE
WHEN LTRIM(RTRIM(col1)) = '' THEN NULL
ELSE LTRIM(RTRIM(col1))
END col1
Maybe something like this?
UPDATE [MyTable]
SET [SomeField] = NULL
WHERE [SomeField] is not NULL
AND LEN(LTRIM(RTRIM([SomeField]))) = 0
here's a regex one for ya.
update table
set col1=null
where col1 not like '%[a-z,0-9]%'
essentially finds any columns that dont have letters or numbers in them and sets it to null. might have to update if you have columns with just special characters.

Resources