码迷,mamicode.com
首页 > 数据库 > 详细

常用sql整理

时间:2014-04-29 16:48:46      阅读:476      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   java   color   os   

1. 存储过程

mamicode.com,码迷
CREATE PROCEDURE [dbo].[bbs_move_createtopic]
@fid smallint,
@iconid smallint,
@curtid INT OUTPUT
AS
BEGIN
    INSERT INTO [topics] ......
    SET @topicid=SCOPE_IDENTITY()
END
mamicode.com,码迷

 

declare @curtid int
exec [createtopic] @fid=@new_fid,@iconid=0,
    @curtid=@curr_topicid OUTPUT

 

2. 游标

mamicode.com,码迷
    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
mamicode.com,码迷

3. 复制表的数据

SELECT * INTO users_bak FROM users

4. group by … having …

mamicode.com,码迷
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
)
mamicode.com,码迷

5. 事务

mamicode.com,码迷
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
mamicode.com,码迷

常用sql整理,码迷,mamicode.com

常用sql整理

标签:style   blog   http   java   color   os   

原文地址:http://www.cnblogs.com/liqipeng/p/3699473.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!