2014-06-11 28 views
0

我只是在使用SQL服務器時發生了一個隨機疑問,我認爲在這裏我可以弄清楚它。 說 - 我有一個條件,我想找出數據庫中滿足我的數據條件的所有列名稱。在SQL服務器中獲取滿足數據where條件的列名稱

示例: - 在SQL-Server DB中有大約20-30個表。現在我需要的是一個查詢,以查找列名稱中包含「Ritesh」作爲數據字段的列名。 我不知道它是否真的有可能擺在首位。

我希望我很清楚。請任何幫助將不勝感激。

謝謝。 Ritesh。

+0

您是否嘗試過使用搜索? http://sackoverflow.com/questions/63953ing/mysql-search-in-all-fields-from-every-table-from-a-database – Andrew

+1

information_schema.columns是你的朋友。 http://msdn.microsoft.com/en-us/library/ms186778.aspx –

+1

@Andrew,該頁面已被刪除,雖然公平,搜索確實產生了數百個結果。 –

回答

1

這應該可以工作,但請注意,這需要一段時間才能在大型數據庫中執行。我假定搜索字符串可能只是包含的數據的一部分,並且正在使用通配符。我覺得這純粹是學術性的,因爲我無法想象一個場景,這是必需的。

--you need to iterate the whole columns of entire table to find the matched record 
--another thing is that you need dynamic sql to find the table name 

DECLARE @Value varchar(50) --value for that find the column Name 
SET @Value = 'Ritesh' 

CREATE TABLE #Table 
(
    TableName Varchar(500),ColumnName Varchar(500), 
    Id int Identity(1,1) --use for iteration 
) 
CREATE TABLE #Results 
(
TableName varchar(500), 
ColumnName varchar(500) 
) 
INSERT INTO #Table 
    SELECT 
     TABLE_SCHEMA + '.' + TABLE_NAME AS TableNam, 
     Column_name AS ColumnName 
    FROM INFORMATION_SCHEMA.COLUMNS 
    WHERE Data_type IN ('char', 'nchar', 'varchar', 'nvarchar') 
--change the datatype based on the datatype of sample data you provide 
-- also remember to change the wildcard, if the input datatype is not a string 

DECLARE @Count Int --total record to iterated 
SET @Count = 0; 


SELECT 
    @Count = COUNT(*) 
FROM #Table 


DECLARE @I int --initial value one to iterate 
SET @I = 1; 


DECLARE @TableName varchar(500) 
SET @TableName = '' 
DECLARE @ColumnName varchar(500) 
SET @ColumnName = '' 


DECLARE @Str nvarchar(1000) 
SET @Str = '' 
DECLARE @param nvarchar(1000) 
SET @param = '' 


DECLARE @TableNameFound varchar(max) 
SET @TableNameFound = '' 


DECLARE @Found bit 
SET @Found = 0; 

WHILE @I<[email protected] 
BEGIN 

SET @Found = 0; 
SELECT 
    @TableName = TableName, 
    @ColumnName = ColumnName 
FROM #Table 
WHERE Id = @I; 
SET @param = '@TableName varchar(500),@ColumnName varchar(500),@Value varchar(50),@TableNameFound varchar(max),@Found bit output' 
SET @str = 'Select @Found=1 From ' + @TableName + ' where ' + @ColumnName + ' Like ' + '''' + '%' + @Value + '%' + '''' 

-- here we are using tablename and actual value to find in table 
EXEC sp_executesql @str, 
        @param, 
        @TableName, 
        @ColumnName, 
        @Value, 
        @TableNameFound, 
        @Found OUTPUT 

    IF @Found=1 
    BEGIN 
    INSERT INTO #Results (TableName, ColumnName) 
    SELECT 
     @TableName, 
     @ColumnName 
    END 

--increment value of @I 
SET @I = @I + 1; 
END 

--Display Results 
SELECT * FROM #Results 

--Clean Up 
DROP TABLE #Table 
DROP TABLE #Results 
+0

感謝您的回覆Raj.I一定會嘗試這個並回復給您。 – Ritesh