在使用存储过程的时候,有时候会需要传一个列表型的参数,比如我想要查询2013、2014、2015这三年的销售记录。通常的解决办法是将传进来的序列进行字符串拼接,并用逗号进行分隔,比如”2013,2014,2015″,然后就需要一个将字符串进行拆分的function。

  1. CREATE FUNCTION FNC_SPLIT(@MYSTR VARCHAR(500), @DELIMITER CHAR(1))
  2. RETURNS @MYTBL TABLE (idx smallint, value varchar(8000))
  3. AS
  4. BEGIN
  5. DECLARE @RET VARCHAR(500)
  6. DECLARE @INDEX INT
  7. DECLARE @COUNTER smallint
  8. --Get the first position of delimiter in the main string
  9. SET @INDEX = CHARINDEX(@DELIMITER,@MYSTR)
  10. SET @COUNTER = 0
  11. --Loop if delimiter exists in the main string
  12. WHILE @INDEX > 0
  13. BEGIN
  14. --extract the result substring before the delimiter found
  15. SET @RET = SUBSTRING(@MYSTR,1, @INDEX-1 )
  16. --set mainstring right part after the delimiter found
  17. SET @MYSTR = SUBSTRING(@MYSTR,@INDEX+1 , LEN(@MYSTR) - @INDEX )
  18. --increase the counter
  19. SET @COUNTER = @COUNTER + 1
  20. --add the result substring to the table
  21. INSERT INTO @MYTBL (idx, value)
  22. VALUES (@COUNTER, @RET)
  23. --Get the next position of delimiter in the main string
  24. SET @INDEX = CHARINDEX(@DELIMITER,@MYSTR)
  25. END
  26. --if no delimiter is found then simply add the mainstring to the table
  27. IF @INDEX = 0
  28. BEGIN
  29. SET @COUNTER = @COUNTER + 1
  30. INSERT INTO @MYTBL (idx, value)
  31. VALUES (@COUNTER, @MYSTR)
  32. END
  33. RETURN
  34. END
  35.  
  36. GO
  37. SELECT value FROM FNC_SPLIT(\'2013,2014,2015\',\',\')
  38. GO
  39. DROP FUNCTION FNC_SPLIT

运行结果图:

image

然后将得到的临时表和数据表进行Join就能拿到想要的数据了。

这里介绍一种的方式:OPENXML,需要用到sp_xml_preparedocument和sp_xml_Removedocument这两个存储过程。

  1. DECLARE @xml varchar(max)
  2. DECLARE @doc int
  3. SET @xml =\'
  4. <?xml version="1.0" encoding="UTF-8"?>
  5. <Request>
  6. <Date Year="2013"/>
  7. <Date Year="2014"/>
  8. <Date Year="2015"/>
  9. </Request>\'
  10. EXEC sp_xml_preparedocument @doc OUTPUT, @xml
  11. CREATE TABLE #Temp([Year] varchar(100))
  12. INSERT INTO #Temp
  13. SELECT [Year] FROM
  14. OPENXML (@doc, \'/Request/Date\', 1)
  15. WITH (Year varchar(100))
  16. EXEC sp_xml_Removedocument @doc
  17. SELECT * FROM #Temp
  18. Drop Table #Temp

运行结果图:

image

结果和上面是一样的,但是使用XML数据作为参数比拼接字符串要更灵活一些。

比如我传入的XML是这样的:

  1. SET @xml =\'
  2. <?xml version="1.0" encoding="UTF-8"?>
  3. <Request>
  4. <Date Year="2013" Date="10"/>
  5. <Date Year="2014" Date="10"/>
  6. <Date Year="2015" Date="10"/>
  7. </Request>\'

我的临时表就可以是这样的:

image

版权声明:本文为zisezhixin原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/zisezhixin/p/4491522.html