我有一个执行“select * from view”的过程,此输出在其中一列中包含一个倒置的逗号。我想做一个replace()来删除额外的反转逗号但是我不能改变“select *”,因为这是一个在不同场景中使用的动态查询。
很明显,以下查询不起作用
select replace(*, '"', '') from ReportRegistry
一些帮助表示赞赏。
我想知道是否有任何方法可以在不知道列名的情况下删除引号。我希望它们从所有列中删除。列名在不同情况下是不同的。
在不同情况下,视图在过程中的定义不同。动态列名称将作为文本添加,并使用sp_executesql执行。
答案 0 :(得分:1)
DECLARE @ColNames NVARCHAR(MAX) = ''
--Dynamically build a list of column names for the view, separated by commas.
SELECT @ColNames = @ColNames +
CASE
--Use the REPLACE function for "String" type data types. Did I leave any data types out?
--Change "x" to the character(s) you want to replace.
WHEN c.DATA_TYPE IN ('VARCHAR', 'CHAR', 'NVARCHAR', 'NCHAR') THEN 'REPLACE([' + c.COLUMN_NAME + '], ''x'', '''') AS [' + c.COLUMN_NAME + '],'
--All other data types.
ELSE '[' + c.COLUMN_NAME + '],'
END
--In addition to user tables, views are included in INFORMATION_SCHEMA.COLUMNS (and in INFORMATION_SCHEMA.TABLES).
FROM INFORMATION_SCHEMA.COLUMNS c
WHERE c.TABLE_NAME = 'ReportRegistry'
--Retain original order of the view's columns.
ORDER BY c.ORDINAL_POSITION
--Remove last comma
SET @ColNames = LEFT(@ColNames, LEN(@ColNames) - 1)
EXEC ('SELECT ' + @ColNames + ' FROM ReportRegistry ')
答案 1 :(得分:0)
select replace(TargetColumnName, '"', '')
,Column2
,Column3
,..... and so on.....
from ReportRegistry
答案 2 :(得分:0)
declare @tbl varchar(max) = 'table_or_view_name'
declare @cols varchar(max) =
(select case when data_type='varchar' then 'REPLACE('+column_name+',''"'','''')' else column_name end+char(10)+','
from information_schema.columns
where table_name = @tbl for xml path(''))
declare @sql varchar(max)='select '+left(@cols,len(@cols)-1)+' from '+@tbl
print @sql
exec(@sql)