2011-02-11 51 views
8

我有一個很長的存儲過程,其中P等於產品表下面的代碼:SQL Server:如何從包含前綴的表中選擇所有內容?

SELECT 
P.*, 
etc1, 
etc2 

這將使我「產品ID」等。

我想用一個前綴,如將其選中:

SELECT 
P.* AS P_*, 
etc1, 
etc2 

這將使我「P_ProductID」等。

這可能嗎?

+0

另一個沒有提到的選項是創建一個正確的形狀的VIEW,並從中選擇 – 2011-02-11 06:00:09

回答

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) 

輸出:

P_ProductID P_Price    P_Description OrderID  Qty 
----------- --------------------- ------------- ----------- ----------- 
1   12.30     apples  11   2 
2   2.40     bananas  11   4 
+0

+1,但是......我沒有看到其他理由想要使用P_ *而不是懶惰。你想誘使他們使用這個?! :) – 2011-02-11 07:40:57

0

我相信 'AS' 只適用於一列。我相信你可以在你的代碼的列標題前添加'P_'。

2

如果您單獨列出所有列,您可以這樣做。

列別名不能用通配符完成。

如果p。*是一個很長的列表,其餘的只是幾列,那麼重命名「其餘」並保留p。*可能會更好。

相關問題