我有一个我想做的选择声明。我要选择
SELECT COLUMN_NAME AS FieldName FROM
INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'table1'
但是我想创建另一个名为 Value 的列,它是 table1 中的特定行,所以我有列名的行和相应的单个值。关于如何解决这个问题的任何想法?
我有一个我想做的选择声明。我要选择
SELECT COLUMN_NAME AS FieldName FROM
INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'table1'
但是我想创建另一个名为 Value 的列,它是 table1 中的特定行,所以我有列名的行和相应的单个值。关于如何解决这个问题的任何想法?
以下查询为每列生成一个值(最小值):
SELECT '''select '+COLUMN_NAME+''' AS FieldName, (select cast(MIN('+COLUMN_NAME+') as varchar(8000)) from '+const.tablename+')'
FROM INFORMATION_SCHEMA.COLUMNS c cross join
(select 'AllCurveNames' as tablename) const
WHERE c.TABLE_NAME = const.tablename
但是,这会为每一行生成一个单独的查询。要将它们组合在一起,您需要一个字符串聚合连接。这就是您在 SQL Server 中的操作方式:
declare @sql varchar(max);
SELECT @sql = (select 'select '''+COLUMN_NAME+''' AS FieldName, (select cast(MIN('+COLUMN_NAME+') as varchar(8000)) from '+const.tablename + ') union all '
FROM INFORMATION_SCHEMA.COLUMNS c cross join
(select WHATEVER as tablename) const
WHERE c.TABLE_NAME = const.tablename
for xml path('')
);
select @sql = LEFT(@sql, len(@sql) - 9);
exec(@sql);
使用交叉连接,如果您只是从两个没有连接的表中选择(即from t1, t2
),则这是隐式的:
SELECT COLUMN_NAME AS FieldName,
Table1.MyField
FROM
INFORMATION_SCHEMA.COLUMNS, Table1
WHERE
TABLE_NAME = 'table1'
AND
MyTable.ID = 123
我实际上想出了一个疯狂的解决方案,但它确实有效:
declare @tbl_name as varchar(255)
declare @field as varchar(255)
declare @val as varchar(255)
declare @SQL as nvarchar(4000)
create table #tbl ( [FieldName][varchar](255), [FieldVal][varchar](255))
set @tbl_name = 'table1'
DECLARE mah_cursor CURSOR FAST_FORWARD
FOR
SELECT COLUMN_NAME FROM
INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @tbl_name
OPEN mah_cursor
FETCH NEXT FROM mah_cursor INTO @field
WHILE @@FETCH_STATUS = 0
BEGIN
set @SQL = 'set @val = (Select top 1 ' + @field + ' from ' + @tbl_name + ')'
print @SQL
exec sp_executesql @query = @SQL, @params = N'@val varchar(255) OUTPUT', @val = @val OUTPUT
insert into #tbl ([FieldName],[FieldVal] ) values (@field, @val)
FETCH NEXT FROM mah_cursor INTO @field
END
CLOSE mah_cursor
DEALLOCATE mah_cursor
select * from #tbl
drop table #tbl
它遍历每个值并添加它。Fast_Forward 功能优化查询以获得高性能