日期:2014-05-18  浏览次数:20446 次

求助SQL 存储过程 返回查询集合的困惑
小弟写了一个常用的存储过程 基本上是经由设置@thatpattern

变量后去查询得到pattern 但是我在运行这个预存程序后 发现

它只能返回一笔数据 但我数据表内 明明有多笔相同的thatpattern的数据

要返回pattern的数据集合 下面的写法却只返回一条 求助该如何写

这里的SQL语法 该怎么写 才能辅合我的要求呢?

SQL code

create PROC aiml2that匹配流程

(

@thatpattern Varchar(5000),

@pattern text OUTPUT)

AS

BEGIN

    SELECT @pattern=pattern FROM aiml2

    WHERE  thatpattern=@thatpattern

END  

Declare @thatpattern Varchar(5000),@pattern Varchar(5000)

Set @thatpattern ='MY FAVORITE SUBJECT IS ARTIFICIAL INTELLIGENCE AND ROBOTS'

select  @pattern=pattern from aiml2  WHERE  thatpattern=@thatpattern order by pattern asc

select  @pattern



------解决方案--------------------
1、怎么用中文命名
2、传入参数不用个括号
3、@pattern有那么大吗还用得到text,尽量不要用text,ntext,最多使用varchar(max)
4、代码要适当换行,要有可读性
5、变量定义最好放在顶端,并做初始化
6、@pattern已经定义,无需再次定义

SQL code

create PROC aiml2that
@thatpattern Varchar(5000),
@pattern     varchar(8000) OUTPUT
AS

BEGIN
    SELECT @pattern=pattern 
    FROM aiml2
    WHERE  thatpattern = @thatpattern
  
    select  @pattern    
END  

--调用示例
DECLARE @thatpattern varchar(50)
DECLARE @pattern     VARCHAR(50)    

SET @thatpattern    = 'a'
SET @pattern        = 'b'

--这里返回的是一个数据结果集
exec dbo.aiml2that @thatpattern,@pattern OUTPUT

------解决方案--------------------
SQL code

作为结果集返回去,在程序中用dataset存储返回前台就可以
create PROC aiml2that匹配流程
(
@thatpattern Varchar(5000)
)
AS
BEGIN

    SELECT  pattern FROM aiml2     WHERE  thatpattern=@thatpattern

END

------解决方案--------------------
变量一次只能得到一个值了

返回多个值直接用查询

SQL code
create PROC aiml2that匹配流程

(

@thatpattern Varchar(5000),

)
as
select pattern  from aiml2  WHERE  thatpattern=@thatpattern order by pattern asc