Thursday, January 6, 2011

Increment rownumbers

SET IDENTITY_INSERT USERS OFF
with cte as
(
select row_number()over(order by userid)Rid ,* from #TAB where userid > 1
)
--select id,9+userid USERID,username from cte WHERE  

update #TAB  set  #TAB.userid= 9+#TAB.userid from cte c where #TAB.userid >1

SET IDENTITY_INSERT USERS on

Tuesday, January 4, 2011

Migration sample

DECLARE @i INT ,@cnt INT ,@roleid INT,@companyid INT,@merchantId INT
SET @i=1
CREATE TABLE #tab (id INT IDENTITY,roleid INT  ,rolename VARCHAR(50),companyId INT, merchantid INT, isdefault BIT)
INSERT INTO #tab SELECT roleid,rolename,companyid,merchantid,isdefault FROM rolemaster
SELECT @cnt=COUNT(*) from #tab
WHILE(@i<=@cnt)
BEGIN
    SELECT @roleid=roleid,@companyid=companyid,@merchantId=merchantid FROM #tab WHERE id =@i

    IF @companyid is not null and @merchantId is not null
        BEGIN
            UPDATE rolemaster SET rolename=rolename+'_'+CAST(ISNULL(@companyid,'') AS VARCHAR(50))+'_'+CAST(ISNULL(@merchantId,'') AS VARCHAR(50)) WHERE roleid=@roleid and isdefault=1 and roleid >5
        END
    ELSE
        BEGIN
            UPDATE rolemaster SET rolename=rolename+'_'+CAST(ISNULL(@companyid,'') AS VARCHAR(50)) WHERE roleid=@roleid and isdefault=1 and roleid >5
        END
    SET @i=@i+1
END

Find the Duplicates using CTE

with cte as
(
select row_number()over(partition by ur.roleid order by ur.roleid )tid ,UR.ROLEID,ROLENAME,U.COMPANYID,U.MERCHANTID,ISDEFAULT,U.USERID
 from rolemaster rm      
inner join userroles ur
on rm.roleid=ur.roleid
inner join users u
on ur.userid=u.userid where isdefault = 1 and rm.roleid > 5
)
select * from cte where tid=1

Remove Dupicates using row_number()

select * from (
select row_number()over(partition by ur.roleid order by ur.roleid )tid ,UR.ROLEID,ROLENAME,U.COMPANYID,U.MERCHANTID,ISDEFAULT,U.USERID
 from rolemaster rm      
inner join userroles ur
on rm.roleid=ur.roleid
inner join users u
on ur.userid=u.userid where isdefault = 1 and rm.roleid > 5 )a where a.tid =1

Finding text for tables and procdures

---------finding text in PROCEDURES

select distinct o.name,o.xtype from syscomments s
inner join sysobjects o on s.id=o.id where s.text like '%screenid%'



---------finding columns in TABLES

SELECT T.NAME,C.NAME  FROM SYS.TABLES T
INNER JOIN SYS.COLUMNS C ON
T.OBJECT_ID=C.OBJECT_ID
WHERE C.NAME LIKE '%screenid%'