现有一需求,需要查询库中所有包含某值,并且某列的值等于指定内容的所有表信息,
如整个库中 查找值=‘123’,并且ID列的值=1的所有表名,123所对应的字段名,
例:表A 有字段
id,name,age,sex
1 123 12 男
2 223 12 男
3 123 12 女
表B有
id,class,name,like
1 234 222 唱歌
1 123 232 跳舞
2 123 123 跑步
现查找含有123的,id=1的数据结果为
表名 列名
表A name
表B class
请大神帮忙,现在可以查询包含123的表信息,但无法加条件(id=1)
查找所有包含123的存储过程为:
CREATE PROCEDURE [dbo].[SP_FindValueInDB]
(
@value VARCHAR(1024)
)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE @sql VARCHAR(1024)
DECLARE @table VARCHAR(64)
DECLARE @column VARCHAR(64)
CREATE TABLE #t (
tablename VARCHAR(64),
columnname VARCHAR(64)
)
DECLARE TABLES CURSOR
FOR
SELECT o.name, c.name
FROM syscolumns c
INNER JOIN sysobjects o ON c.id = o.id
WHERE o.type = 'U' AND c.xtype IN (167, 175, 231, 239)
ORDER BY o.name, c.name
OPEN TABLES
FETCH NEXT FROM TABLES
INTO @table, @column
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sql = 'IF EXISTS(SELECT NULL FROM [' + @table + '] '
SET @sql = @sql + 'WHERE RTRIM(LTRIM([' + @column + '])) LIKE ''%' + @value + '%'' )'
SET @sql = @sql + 'INSERT INTO #t VALUES (''' + @table + ''', '''
SET @sql = @sql + @column + ''')'
EXEC(@sql)
FETCH NEXT FROM TABLES
INTO @table, @column
END
CLOSE TABLES
DEALLOCATE TABLES
SELECT *
FROM #t
DROP TABLE #t
End
GO
如何在此基础上添加条件id=1 或者有没有其他方法实现?
SET @sql = @sql + 'WHERE RTRIM(LTRIM([' + @column + '])) LIKE ''%' + @value + '%'' )'
WHERE后面加条件不行吗?
SET @sql = @sql + 'WHERE ID=1 AND RTRIM(LTRIM([' + @column + '])) LIKE ''%' + @value + '%'' )'