我正在检查事物的尺寸,我想知道从最大到最小的 3 个尺寸。
所以这是我写的有点“神乎其神”的函数:
CREATE FUNCTION dbo.SortDimensions
( @aDim1 udt_Dimension
, @aDim2 udt_Dimension
, @aDim3 udt_Dimension
)
RETURNS @rDimensions TABLE
( Dim1 udt_Dimension
, Dim2 udt_Dimension
, Dim3 udt_Dimension
)
AS
BEGIN
; WITH OrderedDims ( Dimension ) AS (
SELECT @aDim1
UNION ALL SELECT @aDim2
UNION ALL SELECT @aDim3
)
, Pairs ( Name, Value ) AS (
SELECT 'Dim' + CAST( ROW_NUMBER() OVER (ORDER BY( Dimension ) DESC ) AS varchar ), Dimension
FROM OrderedDims
)
INSERT INTO @rDimensions ( Dim1, Dim2, Dim3 )
SELECT MAX(Dim1), MAX(Dim2), MAX(Dim3)
FROM Pairs
PIVOT ( MAX(Value) FOR Name IN ( [Dim1], [Dim2], [Dim3] )) p
RETURN
END
做与此相同的事情不是很多工作:
DECLARE @lDim1 udt_Dimension
DECLARE @lDim2 udt_Dimension
DECLARE @lDim2 udt_Dimension
IF @aDim2 > @aDim1
BEGIN
SELECT @lDim1 = @aDim2
, @lDim2 = @aDim1
END
ELSE
BEGIN
SELECT @lDim1 = @aDim1
, @lDim2 = @aDim2
END
IF NOT @aDim3 > @aDim2
BEGIN
SET @lDim3 = @aDim3
END
ELSE
BEGIN
SET @lDim3 = @lDim2
IF @aDim3 > @lDim1
BEGIN
SET @lDim2 = @lDim1
SET @lDim1 = @aDim3
END
ELSE
BEGIN
SET @lDim2 = @aDim3
END
END
INSERT INTO @rDimensions VALUES ( @lDim1, @lDim2, @lDim3 )
我相信一位 DBA 曾经告诉我,设计 SQL 服务器的人将临时表技术重用于变量,因此它几乎是表和变量之间的清洗。(如果这不是真的,请继续打消我这个想法。)