SQL查询选择前3个字符

时间:2019-11-21 15:44:34

标签: sql sql-server stored-procedures stored-functions

我正在尝试从2个表中选择记录,其中名为DESC(前3个字符)的第一个表列应与第二个表的项目列相匹配。

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

输入: 第一表DESC栏: 值:“ 2AB F YY”

第二表项目列: 值:“ 2AB”

预期输出: 返回所有值2AB的记录

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

请使用保留关键字(例如DESC)作废

SQL Fiddle

MS SQL Server 2017架构设置

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')

查询1

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

Results

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