在使用以下脚本时遇到问题:-
width: 80%; margin: 0 auto;
使用时:-
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
我得到的表中没有_,但是我搜索的表中只有_。
任何人都可以解释为什么它没有返回正确的结果以及sql在后台实际上在做什么吗?
我尝试了各种方法来得出正确的结果,但由于逻辑是合理的,所以无法找出问题所在。
答案 0 :(得分:2)
使用LIKE
运算符时,下划线_
实际上是指任何一个字符。这意味着_
在LIKE
运算符中具有特殊含义。
如果要在带下划线的地方返回表名,则需要在where子句中转义下划线,例如...
WHERE TABLE_NAME like '%\_%' ESCAPE '\'
或者您也可以使用方括号来跳过下划线,而无需使用关键字ESCAPE
WHERE TABLE_NAME like '%[_]%'