1

我创建了一个存储过程来将 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')

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

4

2 回答 2

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 查询语句更改为像这样。

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

无论如何,我不建议您按照自己的方式进行操作。这不是正确的做法。

于 2012-04-30T12:31:38.207 回答
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 as string

于 2012-04-30T12:49:47.550 回答