我有两个表(#temp1
和#temp2
),如下面的代码所示,我正在尝试获取#temp2
表中存在的值的匹配静态ID,但是那里是下面的代码有问题,它返回null staticID
值。
我不确定哪里出错可以有人让我知道我在下面的代码中犯的错误是什么?
BEGIN
CREATE TABLE #temp2
(
staticname VARCHAR(160),
)
INSERT INTO #temp2
VALUES ('Per capita disappearance, carcass weight(456)'),
('Production(286)')
CREATE TABLE #temp1
(
idnum INTEGER IDENTITY(1, 1),
statisticname VARCHAR(256),
staticid INTEGER
)
INSERT INTO #temp1
VALUES ('Per capita disappearance, carcass weight',
'144'),
('Production',
'143')
SELECT
Ltrim (Rtrim (Replace (T2.staticname, Substring(T2.staticname,
Charindex('(', T2.staticname, 0),
Len(T2.staticname) - ( Charindex('(', T2.staticname, 0) - 1 )), ''
))),
T1.staticid
FROM
#temp2 T2
LEFT JOIN
#temp1 T1 ON T2.staticname = T1.statisticname
DROP TABLE #temp1
DROP TABLE #temp2
答案 0 :(得分:1)
#temp1
表的STATISTICNAME
值
Per capita disappearance, carcass weight
Production
与#temp2
表的STATISTICNAME
值
Per capita disappearance, carcass weight(456)
Production(286)
由于使用LEFT JOIN
因此显然会有左表#temp
数据,因此STATICID
的{{1}}列将返回#temp1
如果要使用列进行部分搜索,请使用NULL
运算符。因此,您的LIKE
区块将为:
LEFT JOIN
答案 1 :(得分:1)
您必须更改SELECT LTRIM (RTRIM (REPLACE (T2.STATICNAME,SUBSTRING(T2.STATICNAME, CHARINDEX('(',T2.STATICNAME,0), LEN(T2.STATICNAME)-(CHARINDEX('(',T2.STATICNAME,0)-1)), '')))
,T1.STATICID
FROM #TEMP2 T2 LEFT JOIN #TEMP1 T1 ON LTRIM (RTRIM (REPLACE (T2.STATICNAME,SUBSTRING(T2.STATICNAME, CHARINDEX('(',T2.STATICNAME,0), LEN(T2.STATICNAME)-(CHARINDEX('(',T2.STATICNAME,0)-1)), '')))
= T1.STATISTICNAME
{{1}}
答案 2 :(得分:1)
您没有加入解析后的值。试试这个:
BEGIN
CREATE TABLE #TEMP2
(
STATICNAME Varchar(160),
)
INSERT INTO #TEMP2 VALUES ('Per capita disappearance, carcass weight(456)'),('Production(286)')
CREATE TABLE #TEMP1
(
IDNUM INTEGER IDENTITY(1,1),
STATISTICNAME VARCHAR(256),
STATICID INTEGER
)
INSERT INTO #TEMP1 VALUES ('Per capita disappearance, carcass weight','144'),('Production','143')
;With cteParsed As
(Select *,
LTRIM (RTRIM (REPLACE (T2.STATICNAME,SUBSTRING(T2.STATICNAME,
CHARINDEX('(',T2.STATICNAME,0), LEN(T2.STATICNAME)-
(CHARINDEX('(',T2.STATICNAME,0)-1)), ''))) StaticNameParsed
From #Temp2 T2
)
Select *, T1.STATICID
From cteParsed T2
LEFT JOIN #TEMP1 T1 ON T2.StaticNameParsed = T1.STATISTICNAME
DROP TABLE #TEMP1
DROP TABLE #TEMP2
END
答案 3 :(得分:1)
不确定您要找的是什么,但您的加入失败了
Select A.*,B.*
From #Temp1 A
Join #Temp2 B on ( B.STATICNAME Like A.STATISTICNAME+'%' )