Created
July 26, 2012 05:20
-
-
Save sinairv/3180402 to your computer and use it in GitHub Desktop.
Finding all instances of a GUID in the current database
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE procedure [dbo].[uspFindAllGuid] (@guidToFind uniqueidentifier) | |
as | |
SET NOCOUNT ON | |
-- table variable to store all table and columns containing GUIDs | |
DECLARE @GuidCols AS Table | |
( | |
RowIndex int, | |
TableName varchar(50), | |
ColName varchar(50), | |
IsPrimKey bit | |
) | |
DECLARE @Results AS Table | |
( | |
RowIndex int | |
) | |
DECLARE @maxCounter int | |
DECLARE @counter int | |
DECLARE @tableName varchar(250) | |
DECLARE @colName varchar(250) | |
DECLARE @isPrimKey bit | |
DECLARE @query varchar(MAX) | |
-- populating the table variable | |
INSERT INTO @GuidCols | |
SELECT 0, C.TABLE_NAME, C.COLUMN_NAME, CASE WHEN KCU.CONSTRAINT_NAME IS NULL THEN 0 ELSE 1 END | |
FROM INFORMATION_SCHEMA.COLUMNS C | |
INNER JOIN INFORMATION_SCHEMA.TABLES T ON | |
C.TABLE_NAME = T.TABLE_NAME AND | |
T.TABLE_TYPE = 'BASE TABLE' | |
LEFT JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KCU ON | |
C.COLUMN_NAME = KCU.COLUMN_NAME AND | |
C.TABLE_NAME = KCU.TABLE_NAME AND | |
OBJECTPROPERTY(OBJECT_ID(constraint_name), 'IsPrimaryKey') = 1 | |
WHERE C.DATA_TYPE = 'uniqueidentifier' | |
-- updating an auto-incrementing number in the table variable | |
SET @maxCounter = 0 | |
UPDATE @GuidCols | |
SET @maxCounter = RowIndex = @maxCounter + 1 | |
SET @counter = 0 | |
WHILE @counter < @maxCounter | |
BEGIN | |
SET @counter = @counter + 1 | |
SELECT @tableName=G.TableName, | |
@colName=G.ColName, | |
@isPrimKey=G.IsPrimKey | |
FROM @GuidCols G | |
WHERE RowIndex = @counter | |
SET @query = 'SELECT DISTINCT ' + convert(varchar, @counter) + | |
' FROM ' + QUOTENAME(@tableName) + | |
' WHERE ' + QUOTENAME(@colName) + ' = ' + | |
QUOTENAME(CAST(@guidToFind AS VARCHAR(50)), '''') | |
INSERT INTO @Results | |
EXEC(@query) | |
END | |
SELECT G.TableName, G.ColName, G.IsPrimKey FROM | |
@Results R INNER JOIN @GuidCols G | |
ON G.RowIndex = R.RowIndex | |
ORDER BY G.IsPrimKey DESC | |
GO |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment