我遇到了清理一些数据的需要,我需要在 SQL Server° 中找到一些特定的 guid(即uniqueidentifiers )。
我想出了一个存储过程,它从当前数据库中每个表中的每个 uniqueidentifier 列执行SELECT,如果找到 guid,则返回结果集。
它使用 INFORMATION_SCHEMA 视图来查找所有基表中的所有uniqueidentifier列(与视图相反)。对于每一列,它发出一个选择,返回表的名称和找到它的列。
CREATE PROCEDURE dbo.FindGUID @searchValue uniqueidentifier AS
/*
Search all tables in the database for a guid
6/9/2009: Removed the IF EXISTS to double hit the database
*/
--DECLARE @searchValue uniqueidentifier
--SET @searchValue = '{2A6814B9-8261-452D-A144-13264433864E}'
DECLARE abc CURSOR FOR
SELECT
c.TABLE_NAME, c.COLUMN_NAME
FROM INFORMATION_SCHEMA.Columns c
INNER JOIN INFORMATION_SCHEMA.Tables t
ON c.TABLE_NAME = t.TABLE_NAME
AND t.TABLE_TYPE = 'BASE TABLE'
WHERE DATA_TYPE = 'uniqueidentifier'
DECLARE @tableName varchar(200)
DECLARE @columnName varchar(200)
DECLARE @szQuery varchar(8000)
OPEN ABC
FETCH NEXT FROM abc INTO @tableName, @columnName
WHILE (@@FETCH_STATUS = 0)
BEGIN
SET @szQuery =
'SELECT '''+@tableName+''' AS TheTable, '''+@columnName+''' AS TheColumn '+
'FROM '+@tableName+' '+
'WHERE '+@columnName+' = '''+CAST(@searchValue AS varchar(50))+''''
PRINT 'Searching '+@tableName+'.'+@columnName+'..'
PRINT @szQuery
EXEC (@szQuery)
FETCH NEXT FROM abc INTO @tableName, @columnName
END
CLOSE abc
DEALLOCATE abc
我的问题是:
问题 1
谁能想出一种方法来更改它以执行与 OR 相同的表中的多个 uniqueidentifier 列的搜索,而不是单独的查询
IE
SELECT ... FROM Prices WHERE BookGUID = '{...}'
SELECT ... FROM Prices WHERE AuthorGUID = '{...}'
SELECT ... FROM Prices WHERE PublisherGUID = '{...}'
SELECT ... FROM Prices WHERE StoreGUID = '{...}'
会成为:
SELECT ...
FROM Prices
WHERE BookGUID = '{...}'
OR AuthorGUID = '{...}'
OR PublisherGUID = '{...}'
OR StoreGUID = '{...}'
我尝试在游标内使用游标,但FETCH_STATUS的冲突。
问题 2 谁能想到更好的方法?‡</p>
脚注:
° SQL Server 2000
‡ 受限于在关系数据库中使用唯一标识符的限制。