zoukankan      html  css  js  c++  java
  • 表值函数

    最近在SQL SERVER 项目中使用了一次表值函数,做一下记录。

    所谓表值函数,简单理解为返回一个table的函数。该table是一个 变量表

    我们下面要实现一个功能:

    传入 1,2,3,4,5 这样的字符串参数,

    返回一个记录集合

    1

    2

    3

    4

    5 

    函数实现如下:

     1 CREATE Function Usf_SpliteString2Table (@projectids varchar(512))
     2 RETURNS @hisProjectIDTable TABLE
     3 (
     4  resultRow varchar(64)
     5 )
     6 AS
     7 BEGIN
     8 
     9  DECLARE @tempsub VARCHAR(128)
    10       DECLARE @index INT
    11 
    12       WHILE ( Charindex(',', @projectids) > 0 )
    13         BEGIN
    14             SET @index = Charindex(',', @projectids)
    15             SET @tempsub = Substring(@projectids, 0, @index)
    16             SET @projectIDs = Substring(@projectids, @index + 1, Len(@projectids))
    17 
    18             INSERT INTO @hisProjectIDTable
    19             VALUES      (@tempsub)
    20         END
    21 
    22       IF Len(@projectids) > 0
    23         BEGIN
    24             INSERT INTO @hisProjectIDTable
    25             VALUES      (@projectids)
    26         END
    27 
    28       RETURN
    29 
    30 END

    对功能进行测试

    SELECT * from dbo.Usf_SpliteString2Table('1,2,3,4,5,6')

    并且这个函数返回的表可以和别的表进行联合查询。或者进行匹配

    create table testTable
    (
    value varchar(32)
    )
    
    insert into testTable values ('1,2')
    insert into testTable values('3,4')
    insert into testTable values('5,6')
    insert into testTable values('1,2')
    insert into testTable values('1,2')
    
    select * from testTable a ,
    dbo.Usf_SpliteString2Table('1,2,3,4,5,6') t
    where charindex(t.hisprojectid,a.value) > 0 
  • 相关阅读:
    gradle项目与maven项目互转
    GET和POST两种基本请求方法的区别
    gradle项目打war和jar包
    maven项目打war和jar
    winsw打包jar
    前端
    CentOS
    Vue
    Spring
    Vue
  • 原文地址:https://www.cnblogs.com/songr/p/5009917.html
Copyright © 2011-2022 走看看