问题
CREATE TABLE students
( id INT,
NAME varchar(20)
)
INSERT INTO students(id,name)VALUES(1,'Danny')
INSERT INTO students(id,name)VALUES(2,'Dave')
INSERT INTO students(id,name)VALUES(3,'Sue')
INSERT INTO students(id,name)VALUES(4,'Jack')
INSERT INTO students(id,name)VALUES(5,'Rita')
INSERT INTO students(id,name)VALUES(6,'Sarah')
This is my stored procedure
alter PROCEDURE emp_sp
(
@std_id as VARCHAR(500),
@std_name as varchar(500)
)
AS
begin
SELECT *FROM Students s
WHERE s.id IN(convert(INT,@std_id) ,',')
AND
s.NAME IN(@std_name)
END
GO
Here I execute it manually
EXEC dbo.emp_sp @std_id='1,2,3', @std_name='"Danny","Dave","Sue"'
but I get this error:
Msg 245, Level 16, State 1, Procedure emp_sp, Line 8
Conversion failed when converting the varchar value ',' to data type int.
Anyone can guide me.
回答1:
To get your current approach working, you will need to use Dynamic Sql, which will be incredibly fragile and prone to Sql Injection attacks. Example of this Here
The better way to do this is through Table Valued Parameters:
CREATE TYPE ttStudentIDs AS TABLE
(
ID INT
);
GO
CREATE TYPE ttStudentNames AS TABLE
(
Name VARCHAR(20)
);
GO
CREATE PROCEDURE dbo.emp_sp
(
@stdIds ttStudentIDs READONLY,
@stdNames ttStudentNames READONLY
)
AS
begin
SELECT s.ID, s.Name
FROM Students s
INNER JOIN @stdIds si
ON s.ID = si.ID
UNION
SELECT s.ID, s.Name
FROM Students s
INNER JOIN @stdNames sn
ON s.Name = sn.Name;
END
GO
And called like so:
DECLARE @Ids AS ttStudentIDs;
DECLARE @Names AS ttStudentNames;
INSERT INTO @Ids VALUES (1),(2),(3);
INSERT INTO @Names VALUES ('Danny'),('Dave'),('Sue');
EXEC dbo.emp_sp @Ids, @Names;
SqlFiddle here
来源:https://stackoverflow.com/questions/23284504/how-to-pass-multiple-values-in-single-parameter-and-how-to-convert-varchar-value