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)
相关文档:
从Table 表中取出第 m 条到第 n 条的记录:(Not In 版本)
SELECT TOP n-m+1 *
from Table
WHERE (id NOT IN (SELECT TOP m-1 id from Table ))
--从TABLE表中取出第m到n条记录 (Exists版本)
SELECT TOP n-m+1 * from TABLE AS a WHERE Not Exists
(Select * from (Select Top m-1 * from TABLE orde ......
追加:row_number, rank, dese_rank, ntile
1. row_number: 为查询出来的每一行记录生成一个序号。
SELECT row_number() OVER(ORDER BY field) AS row_n
from tablename;
分页查询:
with t_towtable
as (select row_number over(order by field1) as row_number from tb)
select * from t_rowtable where row_numbe ......
最近一直在用javascript在做项目
可是做着做着
感觉很多功能代码都是重复的。
比如对javascript数组的排序
还有对数组数据的删选以及分组
所以,后来兴致以上来。
一发不可收拾。
写了一个能在javascript中应用的 SQL 库
后来又想,怎么不能用javascript直接连接数据库呢?
又做了一个javascript直连Sql数据的类库 ......
上回说到,操作Object Array
其实还可以这样操作:
var Room = [
{
ID: 'bot',
name: 'test' ......
1、查询两个时间之间
select * from [tablename] where date between \'value1\' and \'value2\'
2、显示最后回复时间
select a.title,a.username,b.adddate from table a,(select max(adddate) adddate from table where table.title=a.title) b
3、日程安排提前5分钟提醒
select * from 日程安排 w ......