I’ve created a stored procedure to split IP address into four different columns.
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
However, I’m getting error when I pass a parameter.
EXEC ipaddress_split @str='191.168.1.1'
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '.1'.
I tried all the below mentioned combinations but with no success.
exec ipaddress_split '191.168.1.1'
exec ipaddress_split 191.168.1.1
exec ipaddress_split ('191.168.1.1')
What is the proper way to pass a parameter to stored procedure?
You don’t have to dynamically generate the query to split the IP address input. You can do something like this.
Stored procedure script:
Execution statement:
Output:
Reason for your issue:
Your dynamic query evaluates to the following format. It is not treating the input to the PARSENAME function as a string.
You have to change the set query statement to like this by including two additional single quotes for each single quote to be displayed on the query.
Your dynamic query will then become like this
I wouldn’t recommend doing it your way anyway. That is not the correct way to do.