sql server中 返回 result table 函式的倆中寫法
1,直接返回表結構資料
USE [CmxSystem]
GO
/****** Object: UserDefinedFunction [dbo].[Fun_CarsTransferList] Script Date: 2018/10/31 星期三 19:21:50 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER function [dbo].[Fun_CarsTransferList](@EntId int ,@UserNo varchar(30),@PageNo int)
returns table
as
return
(
with CarsTransferInfo as(
select c.TransferNo,b.ChineseName,c.FromUser,c.ToUser,c.CrtDate,c.ToEntId,
(case c.Status when '0' then '未審批'when '1' then '審批通過'when '2' then '審批拒絕' end) Status
from CarsTransfer c inner join EnterpriseUsersBaseInfo a
on c.EntId=a.EntId
inner join EnterpriseBaseInfo b
on a.EntId=b.ID
where
SELECT TOP 20 * FROM ( SELECT ROW_NUMBER () OVER (ORDER BY id ASC) RowNumber ,c.TransferNo,c.ChineseName,c.FromUser,c.ToUser,c.CrtDate,c.ToEntId, c. Status,b.name from CarsTransferInfo c inner join BaseInfo b on c.ToEntId= b.ID ) A WHERE A.RowNumber > (@PageNo - 1) * 20
)
2,返回表函式中需要使用變數做一些判斷的方法在返回表資料
USE [CmxSystem] GO /****** Object: UserDefinedFunction [dbo].[Fun_AccountEntry] Script Date: 2018/10/31 星期三 19:23:45 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER FUNCTION [dbo].[Fun_AccountEntry]( @RdNo varchar(30),@EntId int) RETURNS @Table TABLE( RdNo varchar(20), EntId int , Amount int, CrtDate datetime, Remark varchar(50), PayDocNo varchar(30), AccoutType varchar(30), CarsVin varchar(20), WhCode varchar(20), ArCode varchar(20) ) AS BEGIN DECLARE @str char select @str = LEFT(@RdNo,1) if (@str)='R'
INSERT @Table select top 1 a.RdNo,a.EntId,a.Amount,a.CrtDate,a.Remark,a.PayDocNo, (CASE b.AccoutType WHEN '1' THEN '充值' WHEN '2' THEN '費用' WHEN '3' THEN '預約' WHEN '4' THEN '退款' END) as AccoutType ,b.CarsVin,'','' from EnterpriseRechargeDetm a inner join AccountEntry b on a.RdNo = b.BillNo where [email protected] and [email protected] if (@str)='O' INSERT @Table select a.BillNo,a.EntId,a.Amount,a.CrtDate,'','',b.WhCode,b.ArCode, (CASE a.AccoutType WHEN '1' THEN '充值' WHEN '2' THEN '費用' WHEN '3' THEN '預約' WHEN '4' THEN '退款' END) as AccoutType, a.CarsVin from AccountEntry a inner join OrderDetm b on a.BillNo=b.OrderNo where [email protected] and [email protected]
if (@str)='I' INSERT @Table select a.BillNo,a.EntId,a.Amount,a.CrtDate,'','',b.WhCode,b.ArCode, (CASE a.AccoutType WHEN '1' THEN '充值' WHEN '2' THEN '費用' WHEN '3' THEN '預約' WHEN '4' THEN '退款' END) as AccoutType ,a.CarsVin from AccountEntry a inner join OrderDetm b on a.BillNo=b.OrderNo where [email protected] and [email protected] RETURN END總結:應為函式中不能建立臨時表所以使用該方法
RETURNS @Table TABLE( RdNo varchar(20), EntId int , Amount int, CrtDate datetime, Remark varchar(50), PayDocNo varchar(30), AccoutType varchar(30), CarsVin varchar(20), WhCode varchar(20), ArCode varchar(20) ) 相當於就是建立了臨時表
在使用 insert @Table select * from table 的方法吧資料查出來賦值給新建的表中在返回