为什么 information_schema 使用 like 运算符返回格式错误的结果?

Why does the informationschema bring back malformed resuts with a like operator?

我在使用以下脚本时遇到问题:-

USE master

DECLARE @COMPANY CHAR(3)
declare @createdatabase char(50)
declare @fromdatabase char (50)
declare @sql1 char(100)
declare @logicaldatabasename Char(100)
declare @logicaldatabaselog char (100)

set @fromdatabase = 'a'
set @createdatabase = 'b'

SET @COMPANY = 'PUK'

;with q as (
SELECT [name] [logical_name]
FROM sys.[master_files]
WHERE [database_id] = DB_ID(@fromdatabase))
select @logicaldatabasename = q.[logical_name]
from q
where q.[logical_name] not like '%log%'
;with q as (
SELECT [name] [logical_name]
FROM sys.[master_files]
WHERE [database_id] = DB_ID(@fromdatabase))
select @logicaldatabaselog = q.[logical_name]
from q
where q.[logical_name] like '%log%'

select @logicaldatabasename AS LOGICALDATABASENAME, @logicaldatabaselog AS LOGICALDATABSELOG

--BACKUP DATABASE @fromdatabase
--TO DISK = '\folder\'+@fromdatabase+'.bak'
Set @sql1 = 'CREATE DATABASE '+@createdatabase
Exec (@sql1)
RESTORE DATABASE @createdatabase FROM DISK = '\flder\DANTEST.bak' 
WITH MOVE @logicaldatabasename TO 'folder\b.mdf',
MOVE @logicaldatabaselog TO '\folder\b_log.ldf',
REPLACE 
select * from sys.master_files where database_id = db_id(@createdatabase)
;
go
use b
go
;
DECLARE cCursor CURSOR LOCAL FAST_FORWARD FOR


#NAME?
SELECT
  IST.TABLE_NAME AS tblName
FROM
  nhba_a.INFORMATION_SCHEMA.TABLES IST
WHERE RIGHT(IST.TABLE_NAME,3) <> 'PUK' AND IST.TABLE_TYPE = 'BASE TABLE' and ist.TABLE_NAME like '%_%'

ORDER BY IST.TABLE_NAME

--
DECLARE @tblName VARCHAR(255)
--
DECLARE @sql  NVARCHAR(4000)
DECLARE @crlf CHAR(2)

SET @crlf = CHAR(13) + CHAR(10)

OPEN cCursor
FETCH cCursor
INTO @tblName

WHILE @@fetch_status = 0
BEGIN
if @tblname like '%_%'
SET @sql = 'DROP TABLE '+QUOTENAME(@tblName);
EXEC sp_executesql @sql;

  FETCH cCursor
  INTO @tblName
END

使用这个时:-

SELECT
  IST.TABLE_NAME AS tblName
FROM
  nhba_a.INFORMATION_SCHEMA.TABLES IST
WHERE RIGHT(IST.TABLE_NAME,3) <> 'PUK' AND IST.TABLE_TYPE = 'BASE TABLE' and ist.TABLE_NAME like '%_%'

ORDER BY IST.TABLE_NAME

我找到没有 _ 的表格,但我搜索了只有 _ 的表格。

谁能解释为什么它没有返回正确的结果以及 sql 在后台实际做了什么?

我尝试了多种方法来得出正确的结果,但由于逻辑合理,无法找出问题所在。

当您使用 LIKE 运算符时,下划线 _ 实际上引用任何一个字符。这意味着 _LIKE 运算符具有特殊含义。

如果你想 return table 有下划线的名字,那么你需要在你的 where 子句中转义下划线,比如...

WHERE TABLE_NAME like '%\_%' ESCAPE '\'

或者不用关键字ESCAPE

也可以用方括号转义下划线
WHERE TABLE_NAME like '%[_]%'