CREATE TABLE myTable99 (TABLE_NAME sysname, COLUMN_NAME sysname, Occurs int)
GO
SET NOCOUNT ON
DECLARE @SQL varchar(8000),
@TABLE_NAME sysname,
@COLUMN_NAME sysname,
@Sargable varchar(80),
@Count int
SELECT @Sargable = 'PS'
DECLARE insaneCursor CURSOR FOR
SELECT c.TABLE_NAME, c.COLUMN_NAME
FROM INFORMATION_SCHEMA.Columns c INNER JOIN INFORMATION_SCHEMA.Tables t
ON t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME
WHERE c.DATA_TYPE IN ('char','nchar','varchar','nvarchar','text','ntext')
AND t.TABLE_TYPE = 'BASE TABLE'
OPEN insaneCursor
FETCH NEXT FROM insaneCursor INTO @TABLE_NAME, @COLUMN_NAME
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @SQL = 'INSERT INTO myTable99 (TABLE_NAME, COLUMN_NAME, Occurs) SELECT '
+ '''' + @TABLE_NAME + '''' + ','
+ '''' + @COLUMN_NAME + '''' + ','
+ 'COUNT(*) FROM [' + @TABLE_NAME
+ '] WHERE [' + @COLUMN_NAME + '] Like '
+ ''''+ '%' + @Sargable + '%' + ''''
--SELECT @SQL
EXEC(@SQL)
IF @@ERROR <> 0
------ <> means Not Equal To
BEGIN
SELECT @SQL
SELECT * FROM INFORMATION_SCHEMA.Columns WHERE TABLE_NAME = @TABLE_NAME
GOTO Error
END
FETCH NEXT FROM insaneCursor INTO @TABLE_NAME, @COLUMN_NAME
END
SELECT * FROM myTable99 WHERE Occurs <> 0
Error:
CLOSE insaneCursor
DEALLOCATE insaneCursor
GO
DROP TABLE myTable99
GO
SET NOCOUNT OFF
以下存储过程将搜索字符串“PS”并返回 COLUMN_NAME 和 TABLE_NAME 但我想要相应列中 PS 的 ID 值
前任:
ID NAME
2 PW
3 PS
现在存储过程仅返回 COLUMN_NAME,TABLE_NAME 但当我搜索字符串“PS”以及 COLUMN_NAME 和 TABLE_NAME 时,我需要 ID 为 3
我试过了
SELECT @SQL = 'INSERT INTO myTable99 (TABLE_NAME, COLUMN_NAME, Occurs) SELECT *'
+ 'FROM [' + @TABLE_NAME
+ '] WHERE [' + @COLUMN_NAME + '] Like '
+ ''''+ '%' + @Sargable + '%' + ''''
但是即使在表中找不到字符串,存储过程也会返回数据库中的所有表和列名
我的表99
TABLE_NAME COLUMN_NAME Occurs
project projectname 2
task name 1
现在我需要一个名称为 ID 的新列,它在表项目中获取项目名称“PS”的 ID
预期结果:
假设表 Project 有 PS 条目
表名:项目
列:
ID projectname
2 PR
3 PS
现在存储过程将返回Table_Name=Project
,column_Name=projectname
但不是 Id,我需要字符串 PS 的 ID,即 3
结果:当我搜索 string='PS'
ID TABLE_NAME COLUMN_NAME Occurs
3 Project projectname 1