我创建了以下商店程序:
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查询执行此过程时,它正常工作
它仅通过程序提供错误。
答案 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'