我想循环遍历数据库中所有可用表的列,以检查哪些列包含字符串“Kroki Homes”。
我有约。我的数据库中有56个表。因此很难检查这56个表的所有列。有什么简单的方法可以在sql server中实现吗?
答案 0 :(得分:1)
您可以创建一个过程,并可以传递字符串进行搜索。我发现这可能会对你有所帮助。
CREATE PROC [dbo].[SearchDataFromAllTables] (@SearchStr NVARCHAR(100))
AS
BEGIN
SET NOCOUNT ON;
CREATE TABLE #Results
(
ColumnName NVARCHAR(370),
ColumnValue NVARCHAR(3630)
)
DECLARE @TableName NVARCHAR(256)
, @ColumnName NVARCHAR(128)
, @SearchStr2 NVARCHAR(110)
SET @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%', '''')
WHILE @TableName IS NOT NULL
BEGIN
SET @ColumnName = ''
SET @TableName = (
SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
AND OBJECTPROPERTY(OBJECT_ID(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)), 'IsMSShipped') = 0
)
WHILE (@TableName IS NOT NULL)
AND (@ColumnName IS NOT NULL)
BEGIN
SET @ColumnName = (
SELECT MIN(QUOTENAME(COLUMN_NAME))
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = PARSENAME(@TableName, 2)
AND TABLE_NAME = PARSENAME(@TableName, 1)
AND DATA_TYPE IN (
'char'
,'varchar'
,'nchar'
,'nvarchar'
)
AND QUOTENAME(COLUMN_NAME) > @ColumnName
)
IF @ColumnName IS NOT NULL
BEGIN
INSERT INTO #Results
EXEC (
'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630)
FROM ' + @TableName + ' (NOLOCK) ' + ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
)
END
END
END
SELECT ColumnName, ColumnValue FROM #Results
END
答案 1 :(得分:0)
您需要编写一个存储过程来扫描所有表。
下面的脚本提供了表格和列。从这里你应该创建一个SQL in-flight并动态地从表中执行SELECT。如果您需要更多详细信息,请告诉我们。
SELECT tb.name AS table_name,
c.name AS column_name,
c.column_id,
tp.name AS column_data_type,
c.max_length,
c.precision,
c.scale,
CASE c.is_nullable WHEN 1 THEN 'YES' ELSE 'NO' END AS is_nullable
FROM sys.tables tb,
sys.columns c,
sys.types tp
WHERE tb.object_id = c.object_id
AND SCHEMA_NAME(tb.schema_id) = 'dbo'
AND c.user_type_id = tp.user_type_id
ORDER BY table_name, column_id;