错误执行存储过程

时间:2013-09-30 06:17:59

标签: sql sql-server stored-procedures

当我试图执行这个存储过程时,它给我一个有效的标识符错误,任何人都可以帮助我吗?

CREATE Proc [dbo].[AddLogtrail]
    @cmodule varchar(100),   
    @caudittype varchar(15),     
    @ctable varchar(100),    
    @cfield varchar(100),    
    @cfieldtype varchar(100),   
    @coriginalval varchar(100),      
    @cnewval    varchar(100),    
    @cuser varchar(100),     
    @creason varchar(100)     AS    

    DECLARE @SQL  varchar (400)     
    set  @SQL = 'Insert into AudittrailLog (ddatetime,cmodulename,caudittype,ctablename,cfieldname,cfieldtype,coriginalval,cnewval,cuser,creason) values ' + 
    '(convert(datetime,GETDATE(),105),'+@cmodule+','+@caudittype+','+@ctable+','+@cfield+','+@cfieldtype+','+@coriginalval+','+@cnewval+','+@cuser+','+@creason+')';
    PRINT @SQL
    Exec @SQL

3 个答案:

答案 0 :(得分:1)

您需要为varchar值添加其他引号

set  @SQL = 'Insert into AudittrailLog (ddatetime,cmodulename,caudittype,ctablename,cfieldname,cfieldtype,coriginalval,cnewval,cuser,creason) values ' + 
    '(convert(datetime,GETDATE(),105),'''+@cmodule+''','''+@caudittype+''','''+@ctable+''','''+@cfield+''','''+@cfieldtype+''','''+@coriginalval+''','''+@cnewval+''','''+@cuser+''','''+@creason+''')';

打印时应该显示如下。

Insert into AudittrailLog ( ddatetime ,cmodulename ,caudittype ,ctablename ,cfieldname ,cfieldtype ,coriginalval ,cnewval ,cuser ,creason) values (convert(datetime,GETDATE(),105),'test','test','test','test','test','test','test','test','test')

也可以像下面那样执行

EXEC (@SQL)

答案 1 :(得分:0)

您需要将每个varchar打包在'':

CREATE Proc [dbo].[AddLogtrail]
    @cmodule varchar(100),   
    @caudittype varchar(15),     
    @ctable varchar(100),    
    @cfield varchar(100),    
    @cfieldtype varchar(100),   
    @coriginalval varchar(100),      
    @cnewval    varchar(100),    
    @cuser varchar(100),     
    @creason varchar(100)     AS    

    DECLARE @SQL  varchar (400)     
    set  @SQL = 'Insert into AudittrailLog (ddatetime,cmodulename,caudittype,ctablename,cfieldname,cfieldtype,coriginalval,cnewval,cuser,creason) values ' + 
    '(convert(datetime,GETDATE(),105),'''+@cmodule+''','''+@caudittype+''','''+@ctable+''','''+@cfield+''','''+@cfieldtype+''','''+@coriginalval+''','''+@cnewval+''','''+@cuser+''','''+@creason+''')';
    PRINT @SQL
    Exec @SQL

我希望我没有错过任何一个'

答案 2 :(得分:0)

您的问题只是样本或实际程序吗?

因为没有理由在此过程中使用动态SQL。您的查询是静态的。这是一个简单的插图,所有领域都是已知的。你为什么不直接使用INSERT语句?