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, January 3, 2012

How to call a user defined function with a default parameter


Today it happened one of my team member called up me and ask me how to call his function where he has used default parameter. The snapshot of his function is like this only..

create function fnTest(@param1 int, @param2 int = 1 )
returns int
as
begin      
      return @param2      
end

His question was how to call this function in select statement, I simple said, u can either pass two parameter while calling this function, if you are doing so then the second default parameter @param2 value  will get replaced by the new one you pass while calling this function.

select dbo.fnTest(2,5)
-----------
5

(1 row(s) affected)

Where as  if you pass only one parameter to the calling funtion then the @param2 will take the dufault value as 1 in this case.

I give him the below mention line for calling the funtion with one parameter as soon as we excute this line of code we got  error message
select dbo.fnTest(7)

Msg 313, Level 16, State 2, Line 1
An insufficient number of arguments were supplied for the procedure or function dbo.fnTest.

Belive me I was not aware of this then somebody from other team sitting behind us told to use default keyword while calling funtion with default parameter.

select dbo.fnTest(1,default)
-----------
1

(1 row(s) affected)

Thanks Shekhar for the solution.

Post Reference: Vikram Aristocratic Elfin Share

Make use of Magic tables with output clause while inserting/updating or Deleting record in your database table objects


There are two magic table provided by SQL server- Inserted and Deleted.

Inserted and Deleted: The inserted table stores copies of the affected rows during INSERT and UPDATE statements. During an insert transaction, new rows are added to the inserted table.  In case of update transaction which is similar to a delete operation followed by an insert operation; the old rows are copied to the deleted table first, and then the new rows are copied to the inserted table.

OUTPUT Clause: The clause returns a copy of the data that you’ve inserted into or deleted from your tables.  OUTPUT clause has accesses to inserted and deleted tables, OUTPUT clause can be used with INSERT, UPDATE, or DELETE to identify the actual rows affected by these statements.

Let’s explore this with the help of an example:

For our explanation we have taken a table ‘User_Tab’ having the following records in it.

select * from user_tab
user_id     user_name                                          active
----------- -------------------------------------------------- ------
1           Kruthika                                           1
2           Orpita                                             1
3           Aalap                                              1
4           Trishona                                           1
5           Shobna                                             1
6           Eekalabya                                          1
7           Fani                                               1
8           Kishalaya                                          1
9           Mrinmoy                                            1
10          Satyajit                                           1

(11 row(s) affected)

INSERT : Now we are trying to insert a new record in it. See the below mentioned code, here we are using OUTPUT clause to show the value which are going to inserted into the table

insert into user_tab(user_name,active)
output INSERTED.user_id,INSERTED.user_name
values ('suranjan','True')
user_id     user_name
----------- --------------------------------------------------
16          suranjan

(1 row(s) affected)

DELETE: Here we are using OUTPUT clause with Deleted magic table of Sql Server to fetch the deleted value.

DELETE user_tab
OUTPUT deleted.user_id,deleted.user_name
WHERE user_name='suranjan'
user_id     user_name
----------- --------------------------------------------------
16          suranjan

(1 row(s) affected)

UPDATE:  In case of update, the old rows are copied to the deleted table first, and then the new rows are copied to the inserted table. See the below code

update user_tab
set user_name = 'Phaneesh'
output deleted.user_name as 'PreviousName' ,inserted.user_name as 'NewName'
where user_name = 'Fani'
PreviousName                                       NewName
-------------------------------------------------- --------------------------------------------------
Fani                                               Phaneesh

(1 row(s) affected)


Post Reference: Vikram Aristocratic Elfin Share

Saturday, December 31, 2011

A Year Value Recall and Looking Frontward to well again Next Year


A Year Value Recall and Looking Frontward to well again Next Year.


2011 was a fantastic year, I evidence achieving many personal high points, which I surly look back to inspire myself for the next 2012 to become more better.


Mumbai Opportunity:

With god grace I get a chance to move to one of the IT city of India. Here I want to mention this city as GREAT BOMBAY. With my experience of living in Mumbai for some time, Mumbai teaches a lot about life.  Probably no other city in India teaches you as that of Mumbai. Mumbai buzzes with activity all through the 24 hours. The life line of Mumbai, the local trains is a great attraction. When you see the Mumbai trains you will believe that efficiency is still there in India. After reaching the office in the toilet everyone enquires the other which one (local) did the other make it i.e. 8:05 or 8:08 while polishing their attire to commence the work.

When you are in this city you will feel that certain sayings like "NOTHING IS IMPOSSIBLE", " SKY IS THE LIMIT", are really true. 2012 is the time to explore more on opportunity this city gives.


Blogging


I again started blogging as year 2011 draw closer to the very last week; I wish that I will continue this habit. This year my target will be 200 articles on SQL server. I am also aim to start few more blog on Entrepreneurship, Economic India and ASP.NET.


Friends


I feel myself very blessed on this front whether from preceding company or in Mumbai I got first-rate friends, I wish I will continue to uphold our friendship no matter for whatsoever.    


Get Fit,at least Exercise if not GYM


This has been an area which I ignored completely this year and end up putting five more Kilos and tummy clearly visible. Less I pen it on this the better. I am going to seriously concentrate on this. This medical keywords really scares… diabetes, blood pressure, heart attack… I don’t want to explore on these keywords.

  

Post Reference: Vikram Aristocratic Elfin Share

Friday, December 30, 2011

BATCH UPDATE IN SQL SERVER. A much relif for those who are working with Production server

BATCH UPDATE  IN SQL SERVER. A much relif for those who are working with Production server

During my deputation to Onsite, once I experienced a situation where a table from the PRODUCTION/LIVE DB needs an updation for a particular column value.

I remember a situation where where a junior SQL devloper execute update statement on that table which contain data in GBs. As a result of that update statement every thing get stopped.

Those of us, who work in the Production / Live DB, know the pain, of firing an update query on a huge table. This is very problematic as this will lead to the following

  • The entire table will be locked by your application , so other users /  application will not be able to perform the DDL on this table
  •  The TempDB will grow huge
  •  A update lock on a table will stop other users , for making changes in the table.

So what is option to resolve this issue?

I create a solution where I am updateing a table with Active cloumn TRUE where ever it gets ‘FALSE’ value in the column.

For demostration purpose our table contain 10 record with the Active column value ‘FALSE’ and we are updating 2 record at a time. So the batch size of updation in our example is 2. U can set your own value depending upon your application useage.

select * from user_tab where active = 'False'
user_id     user_name                                          active
----------- -------------------------------------------------- ------
1           Kruthika                                           0
2           Orpita                                             0
3           Aalap                                              0
4           Trishona                                           0
5           Shobna                                             0
6           Eekalabya                                          0
7           Fani                                               0
8           Kishalaya                                          0
9           Mrinmoy                                            0
10          Satyajit                                           0

(10 row(s) affected)


And we are updating the FALSE value of Active column to TRUE. But here we are updating two record at a time.

declare @cnt int
declare @total_record int
declare @row_processed int
declare @row_count int

select @cnt = 1
select @row_processed = 0
select @total_record=count(*) from parent_tab

while ( @cnt > 0)
begin
      set rowcount 2
      update user_tab
      set active = 'True'
      where active = 'False'

      select @row_count = @@rowcount
     
      if(@row_count = 0)
      begin
            select @cnt = 0
      end        
      else
      begin
            select @row_processed = @row_processed + @row_count
            print 'The total number of rows effected :'+convert(varchar,@row_processed)
      end
end

print 'Update complete'
set rowcount 0

//OUTPUT OF SCRIPT

(2 row(s) affected)
The total number of rows effected :2

(2 row(s) affected)
The total number of rows effected :4

(2 row(s) affected)
The total number of rows effected :6

(2 row(s) affected)
The total number of rows effected :8

(2 row(s) affected)
The total number of rows effected :10

(0 row(s) affected)
Update complete

After execution of this script the result of the table is as follows

select * from user_tab where active = 'False'
user_id     user_name                                          active
----------- -------------------------------------------------- ------

(0 row(s) affected)

So we can see there is no record with ACTIVE column value ‘FALSE’. Let’s check for ACTIVE = ‘TRUE’


select * from user_tab where active = 'True'

user_id     user_name                                          active
----------- -------------------------------------------------- ------
1           Kruthika                                           1
2           Orpita                                             1
3           Aalap                                              1
4           Trishona                                           1
5           Shobna                                             1
6           Eekalabya                                          1
7           Fani                                               1
8           Kishalaya                                          1
9           Mrinmoy                                            1
10          Satyajit                                           1

(10 row(s) affected)

So all records gets updated with ACTIVE status sets to ‘TRUE’.

If you find any problem in understanding this code, revert me at viki.keshari@gmail.com