我想实现一个存储过程,目的是求出一串字符max(1,2,3,4)的值,貌似首先要把max(1,2,3,4)截断,取出1,2,3,4,然后存到一张临时表中,再求max。(min,avg,sum也需要类似的操作)~~希望好心人能给出存储过程的代码啊。
------解决方案--------------------
DECLARE @s VARCHAR(100)='1,2,3,4,5,6'
SELECT t.c.value('.','int') AS col
INTO #tt
from
(SELECT CAST('<x>'+REPLACE(@s,',','</x><x>')+'</x>' AS XML ).query('.') AS name) AS a
CROSS APPLY a.name.nodes('/x') T(c)
SELECT MAX(col),AVG(col),MIN(col),SUM(col)
FROM #tt
------解决方案--------------------
IF OBJECT_ID('tempdb..[##tmp]') is NOT NULL
DROP TABLE ##tmp
GO
declare @string varchar(1000)
set @string='1,2,3,4'
set @string='select * into ##tmp from (select '+replace(@string,',',' as str union all select ')+') a'
Exec(@string)
------------------------------------------------查询----------------------------------------
SELECT MAX([str]) '最大值',MIN([str]) '最小值',AVG([str]) '平均值' ,SUM([str]) '求和' from ##tmp
------------------------------------------------结果----------------------------------------
/*
最大值 最小值 平均值 求和
----------- ----------- ----------- -----------
4 1 2 10
(1 行受影响)
*/