日期:2014-05-17  浏览次数:20463 次

求大侠解决一个问题,分不多了
当用户表被插入一条新用户的记录时,利用触发器建立一个新的用户表,表名是这个用户的用户id,该如何实现呢??
我是菜鸟,有没有大侠能够不为分数来帮帮忙的!!!

------解决方案--------------------
在插入后,先获取ID,然后用动态SQL拼接create table @id 。再EXEC 这个动态语句就可以了。不过你这个需求有点不合理哦。这种创建对数据库管理来说是一种灾难后果。已经不可控了。如果是学习倒没所谓,如果是工作的话你就要多多思考了。
------解决方案--------------------
SQL code

if object_id('cus') is not null drop table cus
go
create table cus(
uname nvarchar(20) not null primary key
)
go
create trigger cus_ins
on cus
for insert
as
begin
    if not exists(select 1 from inserted) return;
    declare @sql nvarchar(max)
    select @sql=isnull(@sql,'')+'if object_id('''+uname+''') is null create table '+uname+'(id int)' from inserted
    exec(@sql)
end
go

insert into cus 
select 'aaaa'
union all select 'bbbb';

select * from aaaa
select * from bbbb

------解决方案--------------------
当插入用户很多的时候,表会变得非常多。

SQL code

USE test
GO
--准备环境
IF OBJECT_ID('t1') IS NOT NULL
    DROP TABLE t1

CREATE TABLE t1    
    (
        id tinyint identity
        ,value varchar(10)
    )
GO
--建立触发器
CREATE TRIGGER tgCreateUserTable
    ON t1
    FOR INSERT
AS 
    DECLARE @UserTableName varchar(20);
    DECLARE @s varchar(100);
    --数字不是有效的表名,所以加上'UserTable'前缀
    SELECT @UserTableName = 'UserTable'+CAST ( id AS varchar)
    FROM inserted;
    --构造创建表的语句
    SET @s = '
    CREATE TABLE ' + @UserTableName +'
    (
        id tinyint identity
    )'
    EXEC(@s)
GO
--插入数据到表t1,测试触发器
INSERT INTO t1
VALUES
    ('x')
--验证触发器正常运行
SELECT name
FROM sys.tables
WHERE name LIKE 'UserTable'+'%'

------解决方案--------------------
探讨

当插入用户很多的时候,表会变得非常多。

SQL code

USE test
GO
--准备环境
IF OBJECT_ID('t1') IS NOT NULL
DROP TABLE t1

CREATE TABLE t1
(
id tinyint identity
,value varchar(10)
)
GO
--建立触发……