Created
November 13, 2014 03:11
-
-
Save menacestudio/44aedf717269ea7b7121 to your computer and use it in GitHub Desktop.
Dynamic and cursor sample
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE TABLE #codes ( code VARCHAR(10)) | |
INSERT INTO #codes( code ) | |
SELECT distinct c.someCode FROM dbo.tbl_Sample c WITH(NOLOCK) WHERE c.isDeleted=0 AND NOT ISNULL(c.parts,'')='C' | |
AND c.someDate1 >= @anotherDate AND c.someDate1 <= @endDate | |
AND c.providerID IN (SELECT userId from #tmpTable) | |
ORDER by c.someCode | |
-- Temp table for output | |
CREATE TABLE #tbl_Sample2 (userid INT, employee VARCHAR(200), type VARCHAR(150), results INT null) | |
INSERT INTO #tbl_Sample2 ( userid , employee , type , results ) | |
SELECT userid, name, type, 0 from #tmpTable | |
UPDATE t SET results=( | |
SELECT COUNT(*) FROM dbo.tbl_Sample3 c WITH(NOLOCK) | |
WHERE providerId=t.userid AND c.isDeleted=0 | |
AND c.sample3Date >= @anotherDate AND c.sample3Date <= @endDate | |
--and MONTH(c.sample3Date)=@month | |
--AND YEAR(c.sample3Date)=@year | |
) FROM #tbl_Sample2 t | |
DECLARE @someCode VARCHAR(10) | |
DECLARE @sqlCursor nVARCHAR(2000) = '' | |
DECLARE crsr_Test CURSOR FOR SELECT code FROM #codes | |
OPEN crsr_Test | |
FETCH NEXT FROM crsr_Test INTO @someCode | |
WHILE @@FETCH_STATUS = 0 | |
BEGIN | |
SET @sqlCursor = 'ALTER TABLE #tbl_Sample2 ADD ['+ @someCode +'] int null ' | |
EXECUTE sp_executesql @sqlCursor | |
SET @sqlCursor='update t set ['+@someCode+']=(select isnull(sum(minutes),0) from tbl_Sample t1 with(nolock) where t1.providerId=t.userid and t1.isdeleted=0 and | |
t1.someCode='''+@someCode+''' and not isnull(t1.parts,'''')=''C'' | |
and t1.someDate1 >=''' + CONVERT(VARCHAR, @anotherDate) +''' and t1.someDate1 <=''' + CONVERT(VARCHAR,@endDate)+ | |
''' ) from #tbl_Sample2 t' | |
EXECUTE sp_executesql @sqlCursor | |
FETCH NEXT FROM crsr_Test INTO @someCode | |
end | |
CLOSE crsr_Test | |
DEALLOCATE crsr_Test | |
ALTER TABLE #tbl_Sample2 DROP COLUMN userid | |
SELECT * FROM #tbl_Sample2 | |
IF OBJECT_ID('tempdb..#codes') IS NOT NULL DROP TABLE #codes | |
IF OBJECT_ID('tempdb..#tbl_Sample2') IS NOT NULL DROP TABLE #tbl_Sample2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment