sql程序给出错误"' TBL'不是公认的内置功能nam"

时间:2014-12-19 08:09:06

标签: sql-server sql-server-2008 stored-procedures sql-server-2008-r2

我创建了以下商店程序:

USE [Att]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [dbo].[test]
 @DEPTNAME varchar(MAX) = '*'
AS
DECLARE @strSql varchar(max)

Set @strSql = 'SELECT DISTINCT  USERINFO.BADGENUMBER,  USERINFO.NAME,DEPARTMENTS.DEPTNAME
               FROM USERINFO INNER JOIN CHECKINOUT ON USERINFO.USERID = CHECKINOUT.USERID 
               LEFT JOIN DEPARTMENTS ON DEPARTMENTS.DEPTID = USERINFO.DEFAULTDEPTID  
               WHERE DEPARTMENTS.DEPTNAME = '+@DEPTNAME+'
               group by USERINFO.BADGENUMBER,  USERINFO.NAME,DEPARTMENTS.DEPTNAME
              '
EXEC (@strSql)

它已成功创建,但是当我执行此过程时,它会出现错误,如

Msg 195, Level 15, State 10, Line 3
'TBL' is not a recognized built-in function name.

但是当我作为SQL查询执行此过程时,它正常工作

它仅通过程序提供错误。

3 个答案:

答案 0 :(得分:2)

为什么要编写存储过程只是为了执行(错误的,因为你错过了WHERE子句中的单引号)连接的SQL字符串?试试这个:

USE [Att]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[test]
    @DEPTNAME varchar(MAX) = '*'
AS BEGIN
  SELECT DISTINCT  
      USERINFO.BADGENUMBER,        
      USERINFO.NAME,
      DEPARTMENTS.DEPTNAME
  FROM USERINFO 
      INNER JOIN CHECKINOUT ON USERINFO.USERID = CHECKINOUT.USERID 
      LEFT JOIN DEPARTMENTS ON DEPARTMENTS.DEPTID = USERINFO.DEFAULTDEPTID  
  WHERE DEPARTMENTS.DEPTNAME = @DEPTNAME
  GROUP BY 
      USERINFO.BADGENUMBER, USERINFO.NAME, DEPARTMENTS.DEPTNAME
END

这些问题几乎总是发生在人们而不是使用正确的SQL尝试使用连接SQL来做事情时。这几乎总会导致问题。

答案 1 :(得分:1)

在附加参数之前,您似乎错过了引号。试试吧

Set @strSql = 'SELECT DISTINCT  USERINFO.BADGENUMBER,  USERINFO.NAME,DEPARTMENTS.DEPTNAME
           FROM USERINFO INNER JOIN CHECKINOUT ON USERINFO.USERID = CHECKINOUT.USERID 
           LEFT JOIN DEPARTMENTS ON DEPARTMENTS.DEPTID = USERINFO.DEFAULTDEPTID  
           WHERE DEPARTMENTS.DEPTNAME = '''+@DEPTNAME+'''
           group by USERINFO.BADGENUMBER,  USERINFO.NAME,DEPARTMENTS.DEPTNAME
          '

虽然我同意@Thorsten的意见,除非绝对必要,否则不要使用连接的sql进行查询。

答案 2 :(得分:1)

问题是@DEPTNAME

的引号

试试这个

Set @strSql = 'SELECT DISTINCT  USERINFO.BADGENUMBER,  USERINFO.NAME,DEPARTMENTS.DEPTNAME
               FROM USERINFO INNER JOIN CHECKINOUT ON USERINFO.USERID = CHECKINOUT.USERID 
               LEFT JOIN DEPARTMENTS ON DEPARTMENTS.DEPTID = USERINFO.DEFAULTDEPTID  
               WHERE DEPARTMENTS.DEPTNAME = '''+@DEPTNAME+'''
               group by USERINFO.BADGENUMBER,  USERINFO.NAME,DEPARTMENTS.DEPTNAME'