alter trigger createscore
on examlist
for insert
as
declare @examtime varchar(10),@examlistid int
begin
if @@rowcount!=0
begin
select @examtime=考试时间,@examlistid=ExamlistID from examlist
create table @examtime
(StudentID varchar(20),
@examlistid int,
constraint FK_StudentID foreign key(StudentID)references student(StudentID)
)
end
end
这样不行,把@examtime改成['+@examtiime+']也不行,在前面加上exec也不行,请高手指教,研究好几天了......

解决方案 »

  1.   

    declare @sql nvarchar(4000)
    set @sql='create table '+@examtime+'
    (StudentID varchar(20),'+
    @examlistid+' int,'+'
    constraint FK_StudentID foreign key(StudentID)references student(StudentID)'
    execute sp_executesql sql
      

  2.   

    将创建sql 存为一个字符串
    用exec 执行
      

  3.   

    alter trigger createscore
    on examlist
    for insert
    as
    declare @examtime varchar(10),@examlistid int
    declare @sqlstr varchar(1000)
    begin
    if @@rowcount!=0
    begin
    select @examtime=考试时间,@examlistid=ExamlistID from examlist
    set @sqlstr = 'create table ' + @examtime +
    '(StudentID varchar(20),
    @examlistid int,
    constraint FK_StudentID foreign key(StudentID)references student(StudentID)
    )'
    exec (@sqlstr)
    end
    end
      

  4.   

    将创建语句存为一个字符串
    用exec 执行语句
      

  5.   

    错误:在将varchar值'create table 20061112
    (studentID varchar(20),'数据类型转换成int 时失败
      

  6.   

    @examlistid 是int啊,不太好吧,最好先用convert(varchar(20),@examlistid)转换下!
      

  7.   

    或者是加个[],形成[@examlistid] int, 的格式!
      

  8.   

    select @examtime=考试时间,@examlistid=ExamlistID from examlist
    你这个查出来的,@examlistid是数字吧
    不能用数字做数据库的字段
      

  9.   

    declare @sqlStr varchar(2000)
    declare @examtime datetime,@examlistid varchar(30)
    select @examtime=t_date,@examlistid=t_id from test
    select @sqlStr = 'create table ['+convert(varchar(30),@examtime)+']
    (StudentID varchar(30) references publisher(pu_Id),
    ['+@examlistid+'] varchar(30)
    )'
    exec(@sqlStr)
      

  10.   

    CREATE TRIGGER CreateScore
    ON ExamList
    FOR INSERT
    AS
    BEGIN
    DECLARE @ExamTime VARCHAR(10),@ExamListId INT
    SELECT @ExamTime=CONVERT(VARCHAR(10),考试时间,120),@ExamListId=ExamListId FROM ExamList
    EXEC('CREATE TABLE [' + @ExamTime + '](StudentID VARCHAR(20),[' + RTRIM(@ExamListId) + '] INT,CONSTRAIN FK_StudentID FROEIGN KEY(StudentID) REFERENCES Student(StudentID))')
    END
    随手敲的,可能有手误因为是 FOR INSERT的触发器,所以不需要检测 INSERTED表是否有值.
      

  11.   

    declare @sql nvarchar(4000)
    set @sql='create table '+@examtime+'
    (StudentID varchar(20),'+
    cast(@examlistid as nvarchar(4000)+' int,'+'
    constraint FK_StudentID foreign key(StudentID)references student(StudentID)'
    execute sp_executesql sql
      

  12.   

    不是字符的转换一下,如:
    '+@examtime+'
    转换成:
    '+ltrim(rtrim(str(@examtime)))+'
      

  13.   

    一般将其它类型转换为 字符型当用rtrim时并不是为了去空格,而是为了进行隐式转换,因为rtrim写起来比cast或convert方便. 当然要进行一些特定格式的转换时还是需要用相应函数.