Skip to main content

I'm not an Idiot. Are you?

I heard my PM saying today "Their are two types of Idiots. One who will take multiple trips to the database to compare value. Others who will take the values in memory and compare then their".

We have a situation. We need to take values from one table and check if it exists in the second table. Depending on weather it exists in the second table or not, we need to display with / without highlight it in the datagrid.


There is one catch. The query is written by the user in one of the application screen and the user has no idea that the 2nd condition table needs to be applied. I know you would debate that we need to create a screen, so that the user will select what is required instead of writing the query. I know... but we need this asap. Screen will be in the next release.


Let me elaborate: Consider that we have table A and table B. Both these tables have ID column. The user writes (on the application screen)

SELECT * FROM A
 
I can check that this ID does not exist in table B by executing
SELECT * FROM A
WHERE A.ID NOT IN
(SELECT DISTINCT ID FROM B)

This query will return all from A which does not exist in B. But I need both that exist and that does not exist and I need to highlight the rows in the datagrid depending on this condition.

You could argue that I can use JOIN. Whats the problem with JOIN?

SELECT A.ID, COUNT (B.ID)
FROM A JOIN B ON A.ID = B.ID
WHERE A.ID = B.ID
GROUP BY A.ID

Remember the user will write a part of the query and we need to add the rest of it. Join query will be difficult to add to an unknown query from the user. The syntax to create a join query can become really complicated as we do not know what the user plans to input. Imagine if he writes a join query we need to have conditions to add our query before WHERE but after ON condition. This can result in complicated things.

Of course I am not going to do multiple trips to the database to compare the values. I don't plan to take one row of A and compare it to all the values of B, that will be the worst thing ever written. I could have taken all the rows from table A and table B and put them in separate datasets. Then i could easily loop through the dataset and figure out if a rows from dataset A exists in dataset B and color code the rows in the datagrid accordingly. But that again would mean more than one round to the database. Isn't this a good solution or do you have any better idea?

I have!

After an hour of brainstorming we decided to use this:-
SELECT A.ID,
CASE
          WHEN (A.ID NOT IN (SELECT B.ID FROM B)
           THEN 'DOES NOT EXIST'
           ELSE 'EXISTS' END AS [STATUS]
FROM A

The output of this query is
A.ID                     STATUS
----------------------------------------------
   1                        EXISTS
   2                        DOES NOT EXIST

Now we can easily color code this in datagrid depending on Status. We did not face the problem we faced with Join. All we did was add the following code before the "From"
,
CASE
          WHEN (A.ID NOT IN (SELECT B.ID FROM B)
           THEN 'DOES NOT EXIST'
           ELSE 'EXISTS' END AS [STATUS]

and added validations so that the user could not enter keywords like "Update, Insert, Delete, Drop, Into..."

Comments

Popular posts from this blog

Insufficient access rights to perform the operation. (Exception from HRESULT: 0x80072098)

While accessing the active directory (AD) and authorization manager (AZMAN) , If you get “   Insufficient access rights to perform the operation. (Exception from HRESULT: 0x80072098)  “ message check the    account that is being used to get the LDAP query from AD .  ERROR DETAILS Exception Details:  System.Runtime.InteropServices.COMException: Insufficient access rights to perform the operation. (Exception from HRESULT: 0x80072098) Source Error: Line 154:    'Session("FullName") = System.Security.Principal.WindowsIdentity.GetCurrent.Name.ToString() Line 155: Line 156:    If Not User.IsInRole("Role1") Then Line 157:          Response.Redirect("./Login.aspx") Line 158:    End If  Stack Trace : .... SOLVE IT Steps to do check the app pool rights: Click on the website name that you are having problem with in IIS  In the right panel you will see 'Basic Settings'. Click It. Select the specific pool option and enter the name of the ac

Sql Server database Read_Only / Read_Write

The ALTER DATABASE command allows a database administrator to modify SQL Server databases and their files and filegroups. This includes permitting the changing of database configuration options. Why Read Only ? When you need to ensure that the data is a database is not modified by any users or automated processes, it is useful to set the database into a read-only mode. Once read-only, the data can be read normally but any attempts to create, updated or delete table rows is disallowed. This makes the read-only mode ideal when preparing for data migration, performing data integrity checking or when the data is only required for historical reporting purposes. Make Database Read Only USE  [master] GO ALTER DATABASE  [TESTDB]  SET  READ_ONLY  WITH  NO_WAIT GO Make Database Read/Write USE  [master] GO ALTER DATABASE  [TESTDB]  SET  READ_WRITE  WITH  NO_WAIT GO In case you get the following error message make the database single user: Msg 5070, Level 16, Stat

Do's and Don't SQL

Do's: Writing comments whenever something is not very obvious, as it won’t impact the performance.  (--) for single line  (/*…*/) to mark a section Use proper indentation Use Upper Case for all SQL keywords. SELECT, UPDATE, INSERT, WHERE, INNER JOIN, AND, OR, LIKE. Use BEGIN... END block for multiple statements in conditional code  Use Declare and Set in beginning of Stored procedure Create objects in same database where its relevant table exists otherwise it will reduce network performance. Use PRIMARY key in WHERE condition of UPDATE or DELETE statements as this will avoid error possibilities. If User table references Employee table than the column name used in reference should be UserID where User is table name and ID primary column of User table and UserID is reference column of Employee table. Use select column name instead of select * Use CTE (Common Table Expression); its scope is limited to the next statement in SQL query, instead of temporary tables and der