简体   繁体   中英

SQL Server Select data from table without knowing column names

This is sample data table.

在此处输入图片说明

I want to select values in any rows or any column (equals) = 200 with column names.But we don't know column names .

如果您知道表名,则可以使用SQLServer 2005或更高版本查询INFORMATION_SCHEMA.TABLESINFORMATION_SCHEMA.COLUMNS ,或者使用SQLServer 2000来查询sysobjectssyscolumns来检索表列,之后,您可以根据需要创建完全引用的查询

I think the below T-SQL will get you what you want. It was written against AdventureWorks2012LT. In the future, you can get more specific help by including the SQL create statements with your question (so the responder doesn't have to recreate the tables) (BTW, My example is looking for any field that contains the letter 'S')

DECLARE @column_name nvarchar(200);
DECLARE @statement nvarchar(max);

DECLARE @results TABLE(
id int,
colname nvarchar(200),
value nvarchar(max)
)

DECLARE col_cursor CURSOR FOR
SELECT C.COLUMN_NAME AS col
FROM INFORMATION_SCHEMA.COLUMNS C WHERE C.TABLE_NAME LIKE 'Address'

OPEN col_cursor
FETCH NEXT FROM col_cursor INTO @column_name

WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @column_name
SELECT @statement = N'SELECT AddressID, ''' + @column_name + ''' AS ColName, ' + @column_name + ' AS value FROM SalesLT.[Address] WHERE ' + @column_name + ' LIKE ''%S%''';

INSERT INTO @results
EXEC(@statement);

FETCH NEXT FROM col_cursor INTO @column_name
END

CLOSE col_cursor
DEALLOCATE col_cursor

SELECT * FROM @results

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM