SQL Server 在SQL中可以将varchar强制转换为column_name吗?

6bc51xsx  于 2022-12-17  发布在  其他
关注(0)|答案(1)|浏览(161)

我试图创建一个SQL脚本,它获取一个表并返回所有索引及其选择性百分比。我能够检索表中的每个索引并获得索引所基于的列,但我在对我获得的结果应用索引选择性公式时遇到了麻烦,主要是因为我获得的列名是一个varchar,而当我想运行子查询时,它需要是普通SQL。

so my approach to this was to write dynamic sql in the select statement field names but i can't run the exec function to run dynamic sql.

`select *,
*(select cast((select count(distinct column_name) from employee) as float)/(select count( column_name) from employee) * 100.0) as selectivity*

from
(SELECT distinct OBJECT_NAME(Index_Info.OBJECT_ID) AS TableName
  ,Index_Info.name AS IndexName
  ,Index_Stat.index_type_desc AS IndexType
  ,c.name as column_name

FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, NULL) Index_Stat
INNER JOIN sys.indexes Index_Info ON Index_Info.object_id = Index_Stat.object_id AND Index_Info.index_id = Index_Stat.index_id
INNER JOIN sys.index_columns Index_cols ON Index_Info.object_id = Index_cols.object_id
INNER JOIN sys.tables t ON t.object_id = Index_Info.object_id
INNER JOIN sys.index_columns ic ON ic.object_id = t.object_id AND ic.index_id = Index_Info.index_id
INNER JOIN sys.columns c ON c.object_id = t.object_id AND c.column_id = ic.column_id

where OBJECT_NAME(Index_Info.OBJECT_ID) = 'employee') ix_table`

another approach would be to cast the column_name varchar into a column name datatype but i've had little to no luck on both approaches

P.S: when i change the <column_name> to the name of a field the query is working 100% but this way it gives me the results of one field stretched out over the whole result i want it to signify the selectivity of the column_name that i retrieved in this result row.

Sorry if my wording isn't helpful this is my first question on stackoverflow.

Thanks in advance!
5uzkadbs

5uzkadbs1#

尝试将格式重新设置为N'your_query '。这会将动态sql设置为unicode字符串,并支持varchar和nvarchar

相关问题