2

我有一个包含许多列的表,我想在选择时为每一列添加相同的前缀,我的意思是而不是长代码:

SELECT table.id    AS prefix_id
      ,table.value AS prefix_value
      ,table.content AS prefix_content
      , ...

有简单的方法吗?

4

2 回答 2

2

不可能为所有列添加前缀,除非您手动使用AS(如在您的示例中)。

于 2012-08-05T20:35:08.887 回答
0

我不知道这是否会对您有所帮助,请编写一个脚本来执行此操作。您可以自定义它以传递表名、前缀等

declare 
@tableName varchar(50) = 'school',
@sql varchar(max) = 'SELECT '

Select @sql = @sql+'c.'+c.name+',' from sys.columns c
join sys.tables t on c.object_id = t.object_id
where t.name = @tableName

--MORE PRECISELY
Select @sql = @sql+'c.'+c.name+' as prefix_'+c.name+', ' from sys.columns c
join sys.tables t on c.object_id = t.object_id
where t.name = @tableName

Set @sql = @sql + ' FROM '+@tableName+' c'

print @sql

输出,c.前缀在哪里。可以根据口味修改代码

SELECT c.SchoolID as prefix_SchoolID, 

    c.SchoolName as prefix_SchoolName, 
    c.Address as prefix_Address, 
    c.City as prefix_City, 
    c.State as prefix_State, 
    c.Country as prefix_Country,
    c.PhoneNumber as prefix_PhoneNumber, 
    c.Password as prefix_Password,
    c.CreatedBy as prefix_CreatedBy, 
    c.CreatedOn as prefix_CreatedOn, 
    c.ModifiedBy as prefix_ModifiedBy, 
    c.ModifiedOn as prefix_ModifiedOn, 

FROM school c

注意后面的逗号modifiedOn。您可能需要将其从@sql变量中删除或手动删除

于 2012-08-05T20:54:29.637 回答