加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

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

发布时间:2020-12-12 06:23:43 所属栏目:MsSql教程 来源:网络整理
导读:我在一个很长的存储过程中有以下代码,其中P等于Products表: SELECTP.*,etc1,etc2 哪个会给我“ProductID”等等. 我想用前缀选择它,例如: SELECTP.* AS P_*,etc2 哪个会给我“P_ProductID”等等. 这可能吗? 解决方法 除非您使用动态SQL.虽然需要这样的东西
我在一个很长的存储过程中有以下代码,其中P等于Products表:
SELECT
P.*,etc1,etc2

哪个会给我“ProductID”等等.

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

SELECT
P.* AS P_*,etc2

哪个会给我“P_ProductID”等等.

这可能吗?

解决方法

除非您使用动态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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读