Using COALESCE in SQL view(在 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
这篇关于在 SQL 视图中使用 COALESCE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 SQL 视图中使用 COALESCE
基础教程推荐
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- 无法解决整理冲突 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
