我有一个包含许多列的表,我想在执行select时向每列添加相同的前缀,我的意思是代替长代码:
SELECT table.id AS prefix_id
,table.value AS prefix_value
,table.content AS prefix_content
, ...
有一种简单的方法可以做到吗?
答案 0 :(得分:2)
除非您使用AS
手动执行此操作,否则无法为所有列添加前缀(如示例所示)。
答案 1 :(得分: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
变量或manaually