Minhal
Minhal

Reputation: 85

Sql query for selecting the first 3 characters

I am trying to select the records from 2 tables in which the 1st table column named DESC (first 3 characters) should match with the project column of the 2nd table.

select SUBSTRING(a.[DESC],1,3) from Table1 a
left outer join Table2 b
on a.[DESC] = b.project
where SUBSTRING(a.[DESC],1,3) like b.project

Input: 1st Table DESC Column: Value: '2AB F YY'

2nd Table Project Column: Value: '2AB'

Expected Output: Return all the records of value 2AB

Upvotes: 0

Views: 6392

Answers (2)

Amira Bedhiafi
Amira Bedhiafi

Reputation: 1

PLEASE VOID USING RESERVED KEYWORDS LIKE DESC

SQL Fiddle

MS SQL Server 2017 Schema Setup:

CREATE TABLE Table1 ([DESC] varchar(255))
CREATE TABLE Table2 (Project varchar(255))
INSERT INTO Table1([DESC])values('2AB F YY')
INSERT INTO Table2(Project)values('2AB')

Query 1:

select SUBSTRING(a.[DESC],1,3)
from Table1 a
join Table2 b
on SUBSTRING(a.[DESC],1,3) = b.project

Results:

|     |
|-----|
| 2AB |

Upvotes: 1

Suresh Gajera
Suresh Gajera

Reputation: 362

select SUBSTRING(a.[DESC],1,3),* from Table1 a
join Table2 b
on SUBSTRING(a.[DESC],1,3) = b.project

Upvotes: 3

Related Questions