Tuesday, February 21, 2017

How to update multiple columns with multiple rows with different values using single query


Let's say a table named Audit_Table have 3 columns: AuditId, Old value and New Value 

Select * from Audit_Table

AuditId     Old Value                             New Value
----------- ----------------------       ------------------------
1             1                                        2   
2             3                                        4 
2             5                                        6
3             7                                        8


And, we have one more table named Department_Table with the following columns DepartmentId and Department Name

Select * from Department_Table

DepartmentId  Department_Name
------------        ---------------
1                       Computers 
2                       Electrical
3                       Civil     
4                       Mechanical
5                       Electronic
6                       Chemical  
7                       Bio - Tech
8                       Embeded   

In the above Audit_Table, Old Value and New Value having the values of Department id's and you want to update those values with the Department Names. But you want to update the Audit table with a single query, you don't want to run multiple update statements

Below is the query for which we need top update multiple columns and multiple rows with different values

UPDATE Audit_Table SET [Old Value]= (SELECT Department_Name
                                 FROM Department_Table 
                                 WHERE [Old Value] = DepartmentId),
                          [New Value]= (SELECT Department_Name
                                 FROM Department_Table 
                                 WHERE [New Value] = DepartmentId)

And, output goes like this, in a single query you have updated multiple columns and 'n' number of rows with a different values. 

Select * from Audit_Table

AuditId     Old Value                                          New Value
----------- ----------------------------------- ------------------------
1             Computers                                          Electrical
2             Civil                                                     Mechanical
2             Electronic                                            Chemical  
3             Bio - Tech                                           Embeded   


Sunday, February 5, 2017

Must Declare a Scalar Variable Error - Solved | How to insert apostrophe in SQL Query String

You have to use double apostrophe to insert a single apostrophe in SQL Query String. Below is the sample query where it tries to send mail, in which we have to write a SQL query to fetch the details.

In the SQL query we are using a scalar variable, If we are not converting that in to string format SQL throws an error saying "Must declare a scalar variable" and you cant escape from that error

Lets say, we are using a date time value in where condition then its need to be under apostrophes, when we get the value from scalar variable then that value should be converted in to char to form complete SQL query string.

Instead of doing all patch-ups, you can easily convert that value to character and insert in to the query as below.. 


DECLARE @scalarVariable DATETIME

SET @scalarVariable  = (SELECT SomeValue FROM SomeTable )


DECLARE @tab CHAR(1)= CHAR(9);
DECLARE @fileName VARCHAR(256);
DECLARE @sql nvarchar(MAX);
DECLARE @subject nvarchar(MAX);

SET @fileName = 'SomeFile.xls';
SET @sql = N'SELECT * FROM SomeTable WHERE SomeColumn  >' + ''''+CONVERT(VARCHAR(24),@scalarVariable ,21)+'''';


SET @subject = 'Some Subject';

EXEC msdb.dbo.sp_send_dbmail
@profile_name='SomeProfile'
,@recipients='abcd@gmail.com'
,@subject= @subject
,@body='Some data have been changed'
,@body_format = 'Text'
,@query = @sql
,@query_result_separator =  @tab
,@attach_query_result_as_file = 1
,@query_attachment_filename= @fileName
,@query_result_width = 32767
,@query_result_no_padding = 1



Thursday, February 2, 2017

How to Disable Startup Programs

If we see unwanted applications or programs are opening when we start the computer. its very annoying right :( :(

Ok let's see how we can stop from that or How to Disable Startup Programs.

1. Press Windows Key + R, now you will be able to see Run Dialogue Box  



2. Now, type msconfig in the Run and Click 'OK'

3. Click the Startup Tab in the System Configuration Window, you will get to see all the programs which are               running in the Startup.



4. Search for the program which is starting when window starts, uncheck from the list and click 'Apply' and 'OK'

5. It will ask for the 'Restart' to affect the changes so, restart the computer. Now, you are free from those                   unwanted programs which are annoying you. 



Know your current DataBase Mail Configuration

Its very important to give the correct @Profile_Name which are configured for a Data base while we are executing the sp_send_dbmail.

Sometimes, everything seems to be correct, even though you wont receive mail and you could not figure out what could be the issue.

So, first get to know are you giving correct @Profile_Name or not,  that you can see using the following predefined system functions

EXEC msdb.dbo.sysmail_help_principalprofile_sp;


When we executes the above query you will see different @Profile_Names which are configured.

Wednesday, February 1, 2017

What is SET XACT_ABORT ON | OFF

If you have a 10 SQL statements in a stored procedure, where 10th statement is an update statement which updates time in a table indicating that on that particular time that stored procedure got executed successfully. 

Lets consider a situation where 5th statement got run-time error which leads incorrect results in stored procedure

What happens now, ?

Will the rest of the statements executes till the 10th statements and causing the update to a table saying the job got executed successfully ? The answer is YES

In real scenario this should not happen when ever there is an run-time error the JOB needs to stop at that moment 

Why this background ? 

To stop the execution of the job at that moment of run-time error we use 

SET XACT_ABORT ON 

Before the starting of the Stored Procedure

SET XACT_ABORT OFF

After the last statement of the Stored Procedure.