使用带函数的变量 - SQL

时间:2012-02-07 11:14:26

标签: sql sql-server-2008 sql-server-2005 user-defined-functions

我有返回表的自定义函数 它接受两个varchars,它根据分隔符

拆分varchar
SELECT VALUE FROM dbo.Split('xxx','_') --- working

select abc from abcd a,cde b where a.abc like (SELECT VALUE FROM dbo.Split(b.abc,'_'))-- not working


select abc from abcd a,cde b where a.abc like (SELECT VALUE FROM dbo.Split('xx','_'))-- working

select abc from abcd a,cde b where a.abc like (SELECT b.abc)-- working

如何让不工作的案例发挥作用。

错误我明白了 '。'。

附近的语法不正确

2 个答案:

答案 0 :(得分:2)

使用CROSS APPLY可以将变量用作函数的参数。

SELECT abc
FROM   abcd a
       , cde b
       CROSS APPLY (select VALUE from dbo.Split(b.abc, '_')) f
WHERE  a.abc LIKE f.Value

SELECT  *
FROM    abcd a
        , cde b        
        CROSS APPLY dbo.Split(b.abc, '_') f
WHERE   a.abc LIKE f.Value
  

APPLY运算符允许您为其调用表值函数   查询的外表表达式返回的每一行。

测试脚本

CREATE FUNCTION dbo.Split(@a VARCHAR(4), @b VARCHAR(4)) 
RETURNS TABLE 
AS RETURN
(
  SELECT Value = 'Test'  
)
GO

;WITH abcd (abc) AS (
  SELECT 'Test'
)
, cde (abc) AS (
  SELECT 'Test'
)  
SELECT  *
FROM    abcd a
        , cde b        
        CROSS APPLY (SELECT Value FROM dbo.Split(b.abc, '_')) f
WHERE   a.abc LIKE f.Value

答案 1 :(得分:0)

你试过了吗?

select abc 
from abcd a, cde b 
where a.abc like dbo.Split(b.abc,'_')