在 SQL 视图使用 COALESCE
问题说明
我需要从多个表创建一个视图.视图中的一列必须由表中的多行组成,作为带有逗号分隔值的字符串.
I need to create a view from several tables. One of the columns in the view will have to be composed out of a number of rows from one of the table as a string with comma-separated values.
这是我想做的事情的一个简化示例.
Here is a simplified example of what I want to do.
Customers:
CustomerId int
CustomerName VARCHAR(100)
Orders:
CustomerId int
OrderName VARCHAR(100)
客户和订单之间存在一对多关系.所以给定这个数据
There is a one-to-many relationship between Customer and Orders. So given this data
Customers
1 'John'
2 'Marry'
Orders
1 'New Hat'
1 'New Book'
1 'New Phone'
我想要这样的视图:
Name Orders
'John' New Hat, New Book, New Phone
'Marry' NULL
这样每个人都会出现在表格中,无论他们是否有订单.
So that EVERYBODY shows up in the table, regardless of whether they have orders or not.
我有一个需要转换为该视图的存储过程,但您似乎无法在视图中声明参数和调用存储过程.关于如何将此查询放入视图中的任何建议?
I have a stored procedure that i need to translate to this view, but it seems that you cant declare params and call stored procs within a view. Any suggestions on how to get this query into a view?
CREATE PROCEDURE getCustomerOrders(@customerId int)
AS
DECLARE @CustomerName varchar(100)
DECLARE @Orders varchar (5000)
SELECT @Orders=COALESCE(@Orders,'') COALESCE(OrderName,'') ','
FROM Orders WHERE CustomerId=@customerId
-- this has to be done separately in case orders returns NULL, so no customers are excluded
SELECT @CustomerName=CustomerName FROM Customers WHERE CustomerId=@customerId
SELECT @CustomerName as CustomerName, @Orders as Orders
正确答案
EDIT:修改答案以包含视图的创建.
EDIT: Modified answer to include creation of view.
/* Set up sample data */
create table Customers (
CustomerId int,
CustomerName VARCHAR(100)
)
create table Orders (
CustomerId int,
OrderName VARCHAR(100)
)
insert into Customers
(CustomerId, CustomerName)
select 1, 'John' union all
select 2, 'Marry'
insert into Orders
(CustomerId, OrderName)
select 1, 'New Hat' union all
select 1, 'New Book' union all
select 1, 'New Phone'
go
/* Create the view */
create view OrderView as
select c.CustomerName, x.OrderNames
from Customers c
cross apply (select stuff((select ',' OrderName from Orders o where o.CustomerId = c.CustomerId for xml path('')),1,1,'') as OrderNames) x
go
/* Demo the view */
select * from OrderView
go
/* Clean up after demo */
drop view OrderView
drop table Customers
drop table Orders
go
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /reply/detail/tangibhkf
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
检查邮件是否发送成功
it1352 07-25 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
Android微调工具-删除当前选择
it1352 06-20 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20 -
希伯来语的空格句子标记化错误
it1352 06-22