SQL 2016 新语法 函数 和 with cte as() 结合使用案例

USE [CmxSystem]
GO
/****** Object:  UserDefinedFunction [dbo].[Fun_GetCarBaseInfo]    Script Date: 2018/10/7 17:03:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[Fun_GetCarBaseInfo]
(
  @BrandId int,
  @SeriesID int,
  @CarsType int,
  @EntId  int
)
RETURNS TABLE
AS 
RETURN
(
        --库存表和车俩信息表
	with cte as 
	(
	       select detm.*,car.BrandID,car.CarsType,car.SeriesID from WarehouseStockDetm detm
		   left join CarBaseInfo car
		   on detm.CarsVin=car.CarsVin
		   where detm.Status=2 and detm.ZhiyaStatus!=1 
		  
	),
  	     --申贷从表和申贷主表
	 appcte as
	(
		 select line.* from FinancialCreditCarApplyheader header
		 left join  FinancialCreditCarApplyLine line
		 on line.QcNO=header.QcNO 
		 where header.Status=0 and  header.EntId=@EntId
		 and  line.BrandID=@BrandId and line.CarsType=@CarsType and line.SeriesID=@SeriesID
	 )
	 -- 库存和申贷连接
	 select app.QcNO,c.CarsVin,app.BrandID,cname.BrandName,SeriesName.ID, SeriesName.CarSeriesName,TypeName.ID as TypeNameID,  TypeName.CarType 
	 from appcte app  
	 left join cte  c
	 on  app.BrandID=c.BrandID and app.CarsType=c.CarsType and app.SeriesID=c.SeriesID 
	
	 --品牌名称连接
	 left join  CarBrandBaseInfo cname
	 on  app.BrandID=cname.ID

	 --品牌车系连接
	 left join CarSeriesBaseInfo SeriesName
	 on app.BrandID=SeriesName.BrandId

	 --品牌车型连接
	 left join  CarTypeBaseInfo  TypeName
	 on app.BrandID=TypeName.BrandId
	 
)


 

你可能感兴趣的:(Sql,server,数据库)