需要一些存储过程的帮助

时间:2010-12-04 06:56:45

标签: c# asp.net sql-server

存储过程:

ALTER PROC [Admin].[sp_Ques]    
(
 @QuesID bigint
 )
AS
BEGIN
 IF @QuesID = 0
  SET @QuesID =NULL
SELECT     FQ.QuesID, FQ.Ques,QuesAns 
FROM         Admin.Ques FQ

WHERE   FQ.QuesID = Coalesce(@QuesID,QuesID)

SELECT Language FROM Admin.Language WHERE LanguageID=FQ.LanguageID

END

在第二个Select语句中:

SELECT Language FROM Admin.Language WHERE LanguageID=FQ.LanguageID

在这个语句中,我想从第一个选择语句中获取“FQ.LanguageID”的值,所以我写了这个: -

LanguageID=FQ.LanguageID

显然没有用。它说“多部分标识符”FQ.LanguageID“无法绑定。”

我是否需要将此LanguageID作为参数传递给存储过程,然后将其用作: -

SELECT Language FROM Admin.Language WHERE LanguageID=@LanguageID

如果我不想将LanguageID=FQ.LanguageID作为存储过程的第二个参数传递,我该如何使LanguageID工作?有办法吗?

3 个答案:

答案 0 :(得分:2)

FQ的范围仅限于第一个选择语句。

您的选择包括:

  1. 将AdminLanguageID作为您建议的参数传递
  2. 在先前的声明中检索AdminLanguageID(从...中选择@AdminLanguageID = AdminLanguageID)
  3. 将Admin.Language加入Admin.Ques
  4. 使用子查询(从Admin.Language中选择...,其中AdminLanguageID在(从Admin.Ques中选择AdminLanguageID,其中......)

答案 1 :(得分:2)

也许创建一个局部变量来保存正在检索的LanguageID。在上一个SELECT期间为其分配值。添加TOP 1只会确保if / when在第一个查询中有多个匹配(实际上当@Ques为零或为空时!),在该查询中只返回一个值,从而允许单个值进入变量。

DECLARE @Lang int  --whatever datatype your QuesID is.

SELECT   TOP 1
           FQ.QuesID, FQ.Ques,QuesAns as QuesAns,
           FQ.QuesAns[Answers], FQT.QuesType ,
           FQ.QuesTypeID, FQ.QuesParentID, FQ.Active, FQ.AdminLanguageID
          ,@Lang = FQ.AdminLanguageID
FROM         Admin.Ques FQ
LEFT OUTER JOIN Admin.QuesTypes FQT ON FQT.QuesTypeID=FQ.QuesTypeID
WHERE   FQ.QuesID = Coalesce(@QuesID,QuesID)

SELECT TelerikLanguage FROM Admin.Language 
WHERE AdminLanguageID=@Lang 

答案 2 :(得分:1)

为什么不将它们加入1选择?

ALTER PROC [Admin].[sp_Ques]    
(
 @QuesID bigint
 )
AS
BEGIN
 IF @QuesID = 0
  SET @QuesID =NULL
SELECT     FQ.QuesID, FQ.Ques,QuesAns as QuesAns,FQ.QuesAns[Answers], FQT.QuesType ,FQ.QuesTypeID, FQ.QuesParentID, FQ.Active,FQ.AdminLanguageID, AL.TelerikLanguage
FROM         Admin.Ques FQ
LEFT OUTER JOIN Admin.QuesTypes FQT ON FQT.QuesTypeID=FQ.QuesTypeID
    LEFT JOIN Admin.Language AL ON AL.AdminLanguageID=FQ.AdminLanguageID
WHERE   FQ.QuesID = QuesID OR @QuesID IS NULL

END