首页 > 代码库 > 常用sql整理
常用sql整理
1. 存储过程
CREATE PROCEDURE [dbo].[bbs_move_createtopic] @fid smallint, @iconid smallint, @curtid INT OUTPUT AS BEGIN INSERT INTO [topics] ...... SET @topicid=SCOPE_IDENTITY() END
declare @curtid int exec [createtopic] @fid=@new_fid,@iconid=0, @curtid=@curr_topicid OUTPUT
2. 游标
DECLARE @name NVARCHAR(100), @id DECIMAL, @idcard NVARCHAR(100)=NULL //声明游标 DECLARE cur_correctIdCard CURSOR FOR SELECT ID, NAME, [USER_ID] FROM dbo.old_bbstitle WHERE (USER_ID IS NULL OR LTRIM(NAME)=‘‘) OR (NAME IS NULL OR LTRIM(NAME)=‘‘) //打开游标 OPEN cur_correctIdCard //开始FETCH FETCH NEXT FROM cur_correctIdCard INTO @id,@name,@idcard //0 FETCH 语句成功 //1 FETCH 语句失败或此行不在结果集中 //2 被提取的行不存在 WHILE(@@FETCH_STATUS=0) BEGIN ... ... FETCH NEXT FROM cur_correctIdCard INTO @id,@name,@idcard SET @idcard=NULL END CLOSE cur_correctIdCard DEALLOCATE cur_correctIdCard
3. 复制表的数据
SELECT * INTO users_bak FROM users
4. group by … having …
DELETE FROM dbo.old_clubuser WHERE CLUBUSER_ID IN( SELECT MIN(CLUBUSER_ID) FROM dbo.old_clubuser WHERE CLUBUSER_NAME IS NOT NULL AND CLUBUSER_NICKNAME IS NOT NULL GROUP BY CLUBUSER_NAME,CLUBUSER_NICKNAME HAVING COUNT(CLUBUSER_NAME)>1 )
5. 事务
BEGIN TRANSACTION trans_correctIdCard BEGIN TRY DECLARE @name NVARCHAR(100), @id DECIMAL, @idcard NVARCHAR(100)=NULL COMMIT TRANSACTION trans_correctIdCard PRINT ‘SUCCESS‘ END TRY BEGIN CATCH ROLLBACK TRANSACTION trans_correctIdCard PRINT ‘出错:‘+CAST(@@error AS NVARCHAR(MAX)) PRINT ‘已进行回滚‘ END CATCH
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。