SQL 为主表的谋一条记录,在中间表中同时插入多条数据
有时我们会像下面的情况一样,为主表的谋一条记录,在中间表(T_Stud_Course 表)中同时插入多条数据
T_Student 表
Stud_ID
Name
1
Tom
2
Jack
T_Course 表
Course_ID
Course
1
Chinese
2
English
T_Stud_Course 表
ID
Stud_ID
Course_ID
1
1
1
2
1
2
3
2
2
现在我们可以下面的存储过程来实现:
--为主表的谋一条记录,在中间表中同时插入多条数据
ALTER proc [dbo].[wholeInsert]
(
@insert_val nvarchar(1000), --新增的第一个字段的值(多个用‘,’分隔),如A,B,
@PK_id nvarchar(50), --新增数据的第二个字段值,同时也是删除旧数据的条件(不支持多个)
@col_1 nvarchar(20), --第一个字段名
@col_2 nvarchar(20), --第二个字段名
@Tab nvarchar(20), --表名
)
as
begin
declare @sql varchar(1000)
declare @strVal nvarchar(100)
set @sql='delete from '+@Tab+' where '+@col_2+'='+@PK_id
exec(@sql)
while(len(@insert_val)>0)
begin
set @strVal=substring(@insert_val,1,charindex(',',@insert_val,1)-1)
set @insert_val=substring(@insert_val,charindex(',',@insert_val,1)+1,len(@insert_val)-charindex(',',@insert_val,1))
set @sql='insert into '+@Tab+' ('+@col_1+','+@col_2+') values ('+@strVal+','+@PK_id+')'
exec(@sql)
end
end
执行:
Exec wholeInsert '1,2,','1','Course_ID','Stud_ID','T_Stud_Course'
--表示同时为Stud_ID=1的学生增加两门课程(Course_ID为1和2)
相关文档:
-----------------------------------------------------------------------------------------------------------------------
create table tb(id varchar(3) , pid varchar(3) , name varchar(10))
insert into tb values('001' , null , '广东省')
insert into tb values('002' , '001' , '广州市')
insert i ......
1.什么叫SQL注入?如何防止?请举例说明
答:SQL注入是常见的利用程序漏洞进行攻击的方法。导致sql注入攻击并非系统造成的,主要是程序中忽略了安全因素,利用sql语言漏洞获得合法身份登陆系统
例如:
"Select * from users where name='"+uName+"' and pwd='"+uPwd+"' " ......
常用: Select CONVERT(varchar(100), GETDATE(), 8): 10:57:46
Select CONVERT(varchar(100), GETDATE(), 24): 10:57:47
Select CONVERT(varchar(100), GETDATE(), 108): 10:57:49
Select CONVERT(varchar(100), GETDATE(), 12): 060516 Select CONVERT(varchar(100), GETDATE(), 23): 2006-05-16 ......
方法(1)
SELECT stuff((select ','+ltrim(ColumnName) from #A for xml path('')
),1,1,'')
/*
102,103,104,105
*/
方法(2)
DECLARE @s NVARCHAR(1000)='';
SELECT @s+=ColumnName+',' from #A;
SELECT @s; ......