将参数传递给存储过程时为什么会出错?

时间:2012-04-30 12:24:59

标签: sql sql-server sql-server-2008 stored-procedures

我创建了一个存储过程,将IP地址拆分为四个不同的列。

ALTER PROCEDURE ipaddress_split
(
    @str as varchar(max)
)
AS 
BEGIN
    SET NOCOUNT ON

    DECLARE @query as varchar(max)  
    SET  @query = 'SELECT   parsename('+@str+',4) as A
                        ,   parsename('+@str+',3) as B
                        ,   parsename('+@str+',2) as C
                        ,   parsename('+@str+',1) as D';
    EXEC (@query)
    SET NOCOUNT off
END

但是,当我传递参数时,我收到错误。

EXEC ipaddress_split @str='191.168.1.1'

Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '.1'.

我尝试了下面提到的所有组合但没有成功。

exec ipaddress_split '191.168.1.1'
exec ipaddress_split 191.168.1.1
exec ipaddress_split ('191.168.1.1')

将参数传递给存储过程的正确方法是什么?

2 个答案:

答案 0 :(得分:6)

您不必动态生成查询以拆分IP地址输入。你可以这样做。

存储过程脚本

ALTER PROCEDURE ipaddress_split
(
    @str AS VARCHAR(max)
)
AS  
BEGIN

SET NOCOUNT ON

SELECT  PARSENAME(@str, 4) AS A
    ,   PARSENAME(@str, 2) AS B
    ,   PARSENAME(@str, 3) AS C
    ,   PARSENAME(@str, 1) AS D

SET NOCOUNT OFF

END;

执行声明

EXEC ipaddress_split @str = '191.168.1.1';

输出

A   B   C   D
--- --- --- ---
191 1   168 1

您的问题原因:

您的动态查询评估为以下格式。它不会将PARSENAME函数的输入视为字符串。

SELECT parsename(191.168.1.1,4) as A,parsename(191.168.1.1,3) 
as B,parsename(191.168.1.1,2) as C,parsename(191.168.1.1,1) as D

您必须通过在查询中显示的每个单引号中包含两个额外的单引号来将set query语句更改为这样。

set @query = 'SELECT parsename('''+@str+''',4) as A,parsename('''+@str+''',3) 
as B,parsename('''+@str+''',2) as C,parsename('''+@str+''',1) as D';

您的动态查询将变为这样

SELECT parsename('191.168.1.1',4) as A,parsename('191.168.1.1',3) as
B,parsename('191.168.1.1',2) as C,parsename('191.168.1.1',1) as D

我不建议你这样做。这不是正确的做法。

答案 1 :(得分:1)

set @query = 'SELECT PARSENAME('''+@str+''',4) as A ,PARSENAME('''+@str+''',3) as B,PARSENAME('''+@str+''',2) as C,PARSENAME('''+@str+''',1) as D'
EXEC (@query)

试试这个。它应该工作。

否则,传递参数,如

exec ipaddress_split @str='''191.168.1.1'''

在您的情况下,当您执行查询时,它找不到IP为string