create proc add_news
@strsubject nvarchar(100),
@newstype nvarchar(100),
@strfrom nvarchar(100),
@author nvarchar(100),
@editor nvarchar(100),
@newskey nvarchar(100),
@content ntext,
@ptime datetime,
@filepath nvarchar(100)
as
insert into news(strsubject,newstype,strfrom,author,editor,newskey,content,ptime,filepath)
values(@strsubject,@newstype,@strfrom,@author,@editor,@newskey,@content,@ptime,@filepath)
GO
这是一个添加新闻的存储过程,我想把news换成一个通用的,如@tablename,
怎么修改,谢谢

解决方案 »

  1.   

    insert into news(strsubject,newstype,strfrom,author,editor,newskey,content,ptime,filepath)
    values(@strsubject,@newstype,@strfrom,@author,@editor,@newskey,@content,@ptime,@filepath)
    ->
    exec(
    'insert into '+@tablename+
    '(strsubject,newstype,strfrom,author,editor,newskey,content,ptime,filepath)
    values('+@strsubject+','+@newstype+','+@strfrom+','+@author+','+@editor+','+@newskey+','+@content+','+@ptime+','+@filepath+')')
      

  2.   

    --trycreate proc add_news
    (
    @strsubject nvarchar(100),
    @newstype nvarchar(100),
    @strfrom nvarchar(100),
    @author nvarchar(100),
    @editor nvarchar(100),
    @newskey nvarchar(100),
    @content ntext,
    @ptime datetime,
    @filepath nvarchar(100)
    )
    as
    declare @sql nvarchar(4000)
    set @sql='insert into ['+@tablename+'](strsubject,newstype,strfrom,author,editor,newskey,content,ptime,filepath)'
    set @sql+='values('''+@strsubject+''','''+@newstype+''','''+@strfrom+''','''+@author+''','''+@editor+''','''+
    @newskey+''','''+@content+''','''+@ptime+''','''+@filepath+''')'
    exec(@sql)GO
      

  3.   

    使用動態SQL語句create proc add_news
    @tablename nvarchar(100),
    @strsubject nvarchar(100),
    @newstype nvarchar(100),
    @strfrom nvarchar(100),
    @author nvarchar(100),
    @editor nvarchar(100),
    @newskey nvarchar(100),
    @content ntext,
    @ptime datetime,
    @filepath nvarchar(100)
    as
    Begin
    Declare @S Varchar(8000)
    Select @S = ' insert into ' + @tablename + '(strsubject,newstype,strfrom,author,editor,newskey,content,ptime,filepath)
    values(''' + @strsubject + ''',''' + @newstype + ''',''' + @strfrom + ''',''' + @author + ''',''' + @editor + ''',''' + @newskey + ''',''' + @content + ''',''' + Convert(Varchar(20), @ptime, 120) + ''',''' + @filepath + ''')'
    EXEC(@S)
    End
    GO
      

  4.   

    ljsql(第 1 行: '脑子' 附近有语法错误。) , lzhcxc(天道酬勤)都沒注意到@ptime需要做類型轉換。
      

  5.   

    還有,你需要保證其余的表的結構和news的表結構一致,否則,這個也沒有多大的通用性。