SQL Server:如何从带有前缀的表中选择所有内容?

Ste*_*GSD 9 sql database sql-server stored-procedures

我在一个很长的存储过程中有以下代码,其中P等于Products表:

SELECT
P.*,
etc1,
etc2
Run Code Online (Sandbox Code Playgroud)

哪个会给我"ProductID"等等.

我想用前缀选择它,例如:

SELECT
P.* AS P_*,
etc1,
etc2
Run Code Online (Sandbox Code Playgroud)

哪个会给我"P_ProductID"等等.

这可能吗?

Ric*_*iwi 15

除非您使用动态SQL.虽然需要这样的东西是非常罕见的,你确定需要它吗?

工作实例

create table Products (ProductID int, Price money, Description varchar(10));
insert Products select 1, 12.3, 'apples'
insert Products select 2, 2.4, 'bananas'
create table OrderDetails (OrderID int, ProductID int, Qty int)
insert into OrderDetails select 11,1, 2
insert into OrderDetails select 11,2, 4

declare @sql nvarchar(max)
select @sql = coalesce(@sql+',','') +
    'P.' + QuoteName(Column_name) + ' as ' + QuoteName('P_' + Column_name)
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = 'Products'
order by ORDINAL_POSITION
set @sql = '
select ' + @sql + ', O.OrderID, O.Qty
from Products P
inner join OrderDetails O on P.ProductID = O.ProductID
'
--print @sql   :: uncomment if you need to see it
exec (@sql)
Run Code Online (Sandbox Code Playgroud)

输出:

P_ProductID P_Price               P_Description OrderID     Qty
----------- --------------------- ------------- ----------- -----------
1           12.30                 apples        11          2
2           2.40                  bananas       11          4
Run Code Online (Sandbox Code Playgroud)

  • @Andriy你看到这个问题得分为7分并计算?!我不问你为什么要绳索.你问,我给:) (5认同)