1

我有一个表,其中一些列属于bit数据类型。我只需要选择[BIT]数据类型列和[TRUE].

我有以下代码仅选择[BIT]给定表中的列。

SELECT 
    OBJECT_NAME(c.OBJECT_ID) TableName, c.name ColumnName
FROM 
    sys.columns AS c
JOIN 
    sys.types AS t ON c.user_type_id= t.user_type_id
JOIN
    sys.all_objects as o ON o.object_id = c.object_id
WHERE 
    t.name = 'bit' 
    AND o.name = 'TABLENAME' --this is the table name
ORDER BY 
    c.OBJECT_ID
GO

请告诉我如何只选择具有 [TRUE] 值的那些

谢谢

4

2 回答 2

2

您可以在查询中使用动态 sql 和临时表,以将位类型的列的值返回为真或假。 希望这可以帮助。

DECLARE @SQL nvarchar(max)
SET @SQL='DECLARE @TempTable table (Value bit,Table_Column nvarchar(500))'
SELECT @SQL=@SQL+';INSERT @TempTable (Value,Table_Column) SELECT '+c.name + ','' '+c.name + ' - ' + o.name + 
     ''' FROM ['
         +o.name + ']' 
         FROM sys.columns AS c
JOIN sys.types AS t ON c.user_type_id=t.user_type_id
join sys.all_objects as o on o.object_id = c.object_id
WHERE t.name = 'bit' 
and o.name = 'TABLENAME' --this is the table name
ORDER BY c.OBJECT_ID -- columns

SET @SQL=@SQL+';SELECT Table_Column,Value= CASE Value WHEN 0 THEN ''False'' When 1 THEN ''True'' end FROM @TempTable;' 
print @SQL
EXEC (@SQL)
于 2013-08-20T21:01:28.557 回答
1

This can't be done. the Sys schema only contains information about objects in your database, not about records in a table.

The only way to possibly do this is to take the information you have and loop through each tablename in your DB, opening each table that your above-referenced view returns, and using a "WHERE ColumnName <> 'NULL'" qualifier in your looping view.

于 2013-08-20T19:38:00.703 回答