存储过程中的错误查询

时间:2011-11-20 12:17:58

标签: sql sql-server tsql stored-procedures

所有存储过程

USE [amozeshgah]
GO
/****** Object:  StoredProcedure [dbo].[selectmanageregistercourse] ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[selectmanageregistercourse]
@iddore int,
@stateregister int,
@userid nvarchar(350)
AS
declare @str nvarchar(900)
BEGIN
SET @str= 'SELECT tblUserRegisterDore.id, tblUserRegisterDore.idcourse, tblUserRegisterDore.iddore, tblUserRegisterDore.userid, tblUserRegisterDore.coderegister, tblUserRegisterDore.fish, tblUserRegisterDore.date, tblUserRegisterDore.statefish, tblUserRegisterDore.stateregister, tbluser.name, tbldore.name AS namesubcourse, tblmozedore.name AS namecourse, tbluser.family FROM tblUserRegisterDore INNER JOIN tblmozedore ON tblUserRegisterDore.idcourse = tblmozedore.id INNER JOIN tbldore ON tblUserRegisterDore.iddore = tbldore.id AND tblmozedore.id = tbldore.idmozedore INNER JOIN tbluser ON tblUserRegisterDore.userid = tbluser.userid where  iddore='+convert(nvarchar(100),@iddore)
 if (@stateregister<>-1)
begin
set @str +=' and stateregister='+ convert(varchar(100),@stateregister)
end 
if (@userid <>'-1')
begin
set @str +=' and tblUserRegisterDore.userid='+ @userid
end
EXEC sp_executesql @str 
END

运行查询vlaue @userid时出现错误'无效列名值@user id'

传递的参数

EXEC    @return_value = [dbo].[selectmanageregistercourse]
        @iddore = 3,
        @stateregister = 1,
        @userid = N'fdfsdf'

错误 Msg 207,Level 16,State 1,Line 1 列名称'fdfsdf'无效。

为什么?

1 个答案:

答案 0 :(得分:1)

此处存在许多问题,您显示的文件似乎不是您在服务器上使用的文件。

以下是如何创建SP而不使用动态SQL - 它将更快更容易使用:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[selectmanageregistercourse]
@iddore int,
@stateregister int,
@fish nvarchar(350)
AS
BEGIN
    SELECT tblUserRegisterDore.id, tblUserRegisterDore.idcourse, tblUserRegisterDore.iddore, 
           tblUserRegisterDore.userid, tblUserRegisterDore.coderegister, tblUserRegisterDore.fish, tblUserRegisterDore.date, 
           tblUserRegisterDore.statefish, tblUserRegisterDore.stateregister, tbluser.name, tbldore.name AS namesubcourse, 
           tblmozedore.name AS namecourse, tbluser.family 
    FROM tblUserRegisterDore 
    INNER JOIN tblmozedore ON tblUserRegisterDore.idcourse = tblmozedore.id 
    INNER JOIN tbldore ON tblUserRegisterDore.iddore = tbldore.id AND tblmozedore.id = tbldore.idmozedore 
    INNER JOIN tbluser ON tblUserRegisterDore.userid = tbluser.userid 
    WHERE iddore=@iddore
     AND ((@stateregister =-1) OR (stateregister=@stateregister))
     AND ((@fish ='-1') OR (tblUserRegisterDore.fish=@fish))
END

如果您使用上述

,则之前的评论不再适用

但是,这是一个问题。你有一个varchar并且你没有在你正在创建的动态sql中使用引号。

set @str +=' and tblUserRegisterDore.fish='+ @fish

应该是

set @str +=' and tblUserRegisterDore.fish='''+ @fish + ''''