检查表时使用 LIKE 运算符而不是 IN 运算符
LIKE operator instead of IN operator when checking tables
我正在编写 SQL 脚本,如果在 table 中找到 phone 号码,则添加客户 ID。
下面是我的代码片段:
CREATE TABLE #Customers ( AccountNumber nvarchar(20))
CREATE TABLE #Phones ( Number nvarchar(30))
INSERT INTO #Customers (AccountNumber)
SELECT AccountNumber
FROM CustomerTable
WHERE
(CustomerTable.PhoneNumber IN (SELECT DISTINCT Number FROM #Phones))
OR
(CustomerTable.PhoneNumber2 IN (SELECT DISTINCT Number FROM #Phones))
GO
但是,使用这些语句我只能检查 table 中是否满足确切的记录。例如:
如果Phones.Number有一条记录'123456',CustomerTables.PhoneNumber有一条记录'123456 7',则不会得到这条记录记录,即使它包含数字。
我可以对我当前的代码段进行任何修改,以便将类似的逻辑应用于 LIKE 运算符吗?
这不能直接用 in
运算符完成,但在 exists
运算符中使用查询应该可以做到这一点:
INSERT INTO #Customers (AccountNumber)
SELECT AccountNumber
FROM CustomerTable ct
WHERE EXISTS (SELECT *
FROM #Phones p
WHERE ct.PhoneNumber LIKE '%' + p.Number + '%' OR
ct.PhoneNumber2 LIKE '%' + p.Number + '%')
我想这也行,但我没有测试过。
WITH Customers AS
(
SELECT AccountNumber , Len(PhoneNumber) as PhoneSize
FROM
)
INSERT INTO #Customers (AccountNumber)
SELECT AccountNumber
FROM CustomerTable a
Join Customers b on a.AccountNumber = b.AccountNumber
WHERE
(CustomerTable.PhoneNumber IN (SELECT DISTINCT LEft(Number,b.PhoneSize) FROM #Phones))
OR
(CustomerTable.PhoneNumber2 IN (SELECT DISTINCT LEft(Number,b.PhoneSize) FROM #Phones))
SELECT AccountNumber
FROM CustomerTable c
join #Phones p
on c.PhoneNumber like p.Number + '%' OR c.PhoneNumber2 like p.Number + '%'
我正在编写 SQL 脚本,如果在 table 中找到 phone 号码,则添加客户 ID。
下面是我的代码片段:
CREATE TABLE #Customers ( AccountNumber nvarchar(20))
CREATE TABLE #Phones ( Number nvarchar(30))
INSERT INTO #Customers (AccountNumber)
SELECT AccountNumber
FROM CustomerTable
WHERE
(CustomerTable.PhoneNumber IN (SELECT DISTINCT Number FROM #Phones))
OR
(CustomerTable.PhoneNumber2 IN (SELECT DISTINCT Number FROM #Phones))
GO
但是,使用这些语句我只能检查 table 中是否满足确切的记录。例如: 如果Phones.Number有一条记录'123456',CustomerTables.PhoneNumber有一条记录'123456 7',则不会得到这条记录记录,即使它包含数字。
我可以对我当前的代码段进行任何修改,以便将类似的逻辑应用于 LIKE 运算符吗?
这不能直接用 in
运算符完成,但在 exists
运算符中使用查询应该可以做到这一点:
INSERT INTO #Customers (AccountNumber)
SELECT AccountNumber
FROM CustomerTable ct
WHERE EXISTS (SELECT *
FROM #Phones p
WHERE ct.PhoneNumber LIKE '%' + p.Number + '%' OR
ct.PhoneNumber2 LIKE '%' + p.Number + '%')
我想这也行,但我没有测试过。
WITH Customers AS
(
SELECT AccountNumber , Len(PhoneNumber) as PhoneSize
FROM
)
INSERT INTO #Customers (AccountNumber)
SELECT AccountNumber
FROM CustomerTable a
Join Customers b on a.AccountNumber = b.AccountNumber
WHERE
(CustomerTable.PhoneNumber IN (SELECT DISTINCT LEft(Number,b.PhoneSize) FROM #Phones))
OR
(CustomerTable.PhoneNumber2 IN (SELECT DISTINCT LEft(Number,b.PhoneSize) FROM #Phones))
SELECT AccountNumber
FROM CustomerTable c
join #Phones p
on c.PhoneNumber like p.Number + '%' OR c.PhoneNumber2 like p.Number + '%'