SQL模式和值

我有我想要的选择陈述。我想选择

SELECT COLUMN_NAME AS FieldName FROM   
INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_NAME = 'table1'

不过,我想创建另一个名为Value的列,它是table1中的特定行 所以我有行列的名称和相应的单个值。有关如何解决这个问题的任何想法?

0
额外 编辑
意见: 1
table1中的“特定行”是什么意思?您可以为SQL查询添加常量,只需 SELECT'Value'
额外 作者 N West,

3 答案

我实际上想出了一个疯狂的解决方案,但它的工作原理:

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功能优化了查询的高性能

0
额外

使用交叉联接,如果您只从没有联接的两个表中选择(即,来自t1,t2 的),则隐式交叉联接:

SELECT COLUMN_NAME AS FieldName,
       Table1.MyField
FROM
    INFORMATION_SCHEMA.COLUMNS, Table1
WHERE
    TABLE_NAME = 'table1'
AND
    MyTable.ID = 123
0
额外
额外 作者 marc_s,

以下查询为每列生成一个值(最小值):

    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);
0
额外