常用sql整理
时间:2014-04-29 16:48:46
收藏:0
阅读:476
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
评论(0)