About Me

My photo
Mumbai, Maharastra, India
He has more than 7.6 years of experience in the software development. He has spent most of the times in web/desktop application development. He has sound knowledge in various database concepts. You can reach him at viki.keshari@gmail.com https://www.linkedin.com/in/vikrammahapatra/ https://twitter.com/VikramMahapatra http://www.facebook.com/viki.keshari

Search This Blog

Tuesday, May 22, 2012

Cursoring CTE : Using Cursor with CTE


When I tried to create cursor with the result of CTE, I was greated with the following error:

Incorrect syntax near the keyword 'declare'.

My piece of code was like below:

with myCTE(objId, name) as
(
      select top 5 object_id, name from sys.columns
)

declare myCur cursor for
Select objId, name From myCTE

Msg 156, Level 15, State 1, Line 6
Incorrect syntax near the keyword 'declare'.

This means my expected syntax was incorrect, after a few minute of google I found in one of the blog that  the declare cursor statement needs to be on the top of CTE declarations. So, here’s the correct syntax to define cursor with CTEs:

declare @objId int
declare @name varchar(10)

declare myCur cursor for
with myCTE(objId, name) as
(
      select top 4 object_id, name from sys.columns
)
Select objId, name From myCTE

Open myCur
Fetch next from myCur into @objId, @name

while @@fetch_status <> -1
begin
    print @objId
      print @name
      Fetch next from myCur into @objId, @name
end

close myCur
deallocate myCur
------------OUTPUT---------
117575457
xserver_na
117575457
xdttm_ins
117575457
xdttm_last
117575457
xfallback_

cool finicky learn… 

Post Reference: Vikram Aristocratic Elfin Share

Friday, May 11, 2012

Replicate : prefix '0' (Zero) with numbers

In most of the scenario, we need to prefix '0' (Zero) with numbers.

If my result is 15 then, it should be resulted as 00015
If my result is 2010 then, it should be resulted as 02010

So, the total length should be 5.

If the total length is 5 then '0' should be prefixed based on the result.

declare @para AS varchar(5)
select @para = '15'
select replicate ('0', 5 - len(@para)) +  @para

Result
--------------------
00015

(1 row(s) affected)

/* I want 5.20 should display like 05.20 This means i will append one zero
before the given indexNo */

declare @indexNo as numeric(8,2)
select @indexNo = 5.20
select Cast(Replicate(0,6-Len(@indexNo)) AS varchar(5)) + Cast(@indexNo AS varchar(5))

Result
----------
005.20

(1 row(s) affected)

So Replicate is nothing but repeats a string value a specified number of times


Post Reference: Vikram Aristocratic Elfin Share