代码之家  ›  专栏  ›  技术社区  ›  Danny James

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

  •  1
  • Danny James  · 技术社区  · 6 年前

    我对下面的脚本有问题:

    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
    

    我有没有A的桌子,但我只找了有A的桌子。

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

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

    1 回复  |  直到 6 年前
        1
  •  2
  •   M.Ali    6 年前

    当你使用 LIKE 运算符下划线 _ 实际上是任何一个角色的裁判。意思是 _ 就像 接线员。

    如果要返回带有下划线的表名,则需要在where子句中转义下划线,例如…

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

    或者也可以使用方括号转义下划线而不使用关键字 ESCAPE

    WHERE TABLE_NAME like '%[_]%'