how to pass multiple values in single parameter and how to convert varchar value into integers

我是研究僧i 提交于 2019-12-24 12:22:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!