以下内容只是部分原创,仅是之前收集到的知识。只做记录避免遗忘,具体出处已遗忘。
一、游标结构
总是遗忘游标的结构
declare PeriodDataCursor cursor for select ID , ClassTime from @temptable order by [ClassTime] desc open PeriodDataCursor fetch next from PeriodDataCursor into @ID , @firstClsTime while(@@FETCH_STATUS=0) begin if((select top 1 1 from Mall_EverydayValue where Summary='-初始化' and InPeriod=@ID )=1) begin select 1 ; end fetch next from PeriodDataCursor into @ID , @firstClsTime end close PeriodDataCursor deallocate PeriodDataCursor end
二、级联删除,更新
/* drop table test_sub drop table test_main */ -- 创建测试主表. ID 是主键. CREATE TABLE test_main ( id INT NOT NULL, value VARCHAR(10), PRIMARY KEY(id) ); -- 创建测试子表. CREATE TABLE test_sub ( id INT NOT NULL, main_id INT , value VARCHAR(10), PRIMARY KEY(id) ); --创建外键,使用 ON DELETE CASCADE 选项,删除主表的时候,同时删除子表 -- ON UPDATE CASCADE 级联更新 ALTER TABLE test_sub ADD CONSTRAINT main_id_cons FOREIGN KEY (main_id) REFERENCES test_main(id) ON DELETE CASCADE ON UPDATE CASCADE ; -- 插入测试主表数据. INSERT INTO test_main(id, value) VALUES (1, 'ONE'); INSERT INTO test_main(id, value) VALUES (2, 'TWO'); -- 插入测试子表数据. INSERT INTO test_sub(id, main_id, value) VALUES (1, 1, 'ONEONE'); INSERT INTO test_sub(id, main_id, value) VALUES (2, 2, 'TWOTWO'); --执行删除: DELETE FROM TEST_MAIN WHERE ID = 1; -- 执行更新: update TEST_MAIN set id=5 from TEST_MAIN where id=2 ; -- DELETE FROM test_sub WHERE ID = 1; --最后: SELECT * FROM TEST_MAIN; SELECT * FROM test_sub; --结果子表中就只有ID=5的记录,也就说明级联删除成功和更新成功。
三、获取该所有外键
SELECT 主键列ID=b.rkey ,主键列名=(SELECT name FROM syscolumns WHERE colid=b.rkey AND id=b.rkeyid) ,外键表ID=b.fkeyid ,外键表名称=object_name(b.fkeyid) ,外键列ID=b.fkey ,外键列名=(SELECT name FROM syscolumns WHERE colid=b.fkey AND id=b.fkeyid) ,级联更新=ObjectProperty(a.id,'CnstIsUpdateCascade') ,级联删除=ObjectProperty(a.id,'CnstIsDeleteCascade') FROM sysobjects a join sysforeignkeys b on a.id=b.constid join sysobjects c on a.parent_obj=c.id where a.xtype='f' AND c.xtype='U' and object_name(b.rkeyid)='TEST_MAIN'