Labels

Friday, August 26, 2016

SYS.SQL_MODULES in T-SQL (Catalog View)

The sys.sql_modules system view is a powerful tool for returning object details within a SQL Server database. It allows developers to easily retrieve the definition and metadata for various objects, including Stored Procedures, Replication-filter procedures, Views, and DML Triggers. Additionally, it covers SQL Scalar Functions, Inline Table-valued Functions, Table-valued Functions, and Rules. Using this view is an essential way to audit or search your codebase programmatically.

Columns


object_id
definition
uses_ansi_nulls
uses_quoted_identifier
is_schema_bound
uses_database_collation
is_recompiled
null_on_null_input
execute_as_principal_id

SELECT  object_id, definition, uses_ansi_nulls, uses_quoted_identifier,
                 is_schema_bound,uses_database_collation, is_recompiled,null_on_null_input,                                      execute_as_principal_id
 FROM   sys.sql_modules




Thursday, August 25, 2016

Logical processing order of SELECT statement

When a SQL query executes on SQL Server, it follows a specific sequence known as the Logical Query Processing Order. While we write queries starting with SELECT, SQL Server processes them in a very different order to ensure data is filtered and grouped correctly before being returned. Understanding this flow is essential for writing efficient code and troubleshooting unexpected results. Let’s break down the logical order of a SELECT statement.


1. FROM
2. ON
3. OUTER
4. WHERE
5 GROUP BY
6 CUBE or ROLLUP
7 HAVING
8 SELECT
9 DISTINCT
10 ORDER BY
11 TOP

SQL query to get table names and schema in Database

There are several ways to retrieve table names and their associated schemas within a SQL Server database. Depending on your specific needs—whether you are automating a script or performing a quick manual check—different methods offer different levels of detail. Below, I have outlined some of the most common and effective ways to query your database metadata.

1.
SELECT SCHEMA_NAME(schema_id) 'SchemaName' , name 'TableInDb' 
FROM sys.tables

Return all tables and related schema in selected database



2.
SELECT TABLE_CATALOG ,TABLE_SCHEMA ,TABLE_NAME ,TABLE_TYPE  FROM INFORMATION_SCHEMA.TABLES

this will return more information than first one, it's return VIEWs in Database as well



3.
  SELECT t.name 'TableName' ,s.name 'SchemaName'
  FROM sys.tables AS t
  INNER JOIN sys.schemas AS s
  ON t.[schema_id] = s.[schema_id]

  SELECT t.name 'TableName' ,s.name 'SchemaName'
  FROM sys.tables AS t
  INNER JOIN sys.schemas AS s
  ON t.[schema_id] = s.[schema_id]
  WHERE s.name = N'dbo';







Wednesday, August 24, 2016

UNION and UNION ALL in T-SQL

UNION

The UNION operator is used to combine the result sets of two or more SELECT statements. To use it successfully, you must follow three key rules:

  • Column Consistency: Each SELECT statement must have the same number of columns.

  • Data Compatibility: The corresponding columns in each statement must have similar or compatible data types.

  • Distinct Results: By default, UNION removes duplicate records and returns only distinct values.

UNION ALL

The UNION ALL operator works similarly to UNION, but with one major difference: it retrieves all rows from the selected tables without filtering for duplicates. Because it doesn't spend resources searching for and removing identical records, UNION ALL is significantly faster and more efficient when you know your data is unique or when you specifically want to include every result.  


Use UNION ALL by default if your data is already unique or if you don't mind including duplicate records. Because UNION must perform extra work to ensure only distinct values are returned, it is slower than UNION ALL. Only reach for the standard UNION when you specifically need to filter out overlapping data between your query results.



Friday, August 19, 2016

How to pass parameter to an Exe

When building desktop applications, you often need to pass data between different programs. Fortunately, there is a common method for passing parameters to an executable (.exe) whether you are using WPF or Windows Forms. By leveraging command-line arguments, you can trigger specific behaviors or load specific data into your application upon startup. Below, I’ll show you the universal way to implement this.

1. Add reference System.Diagnostics your class.                                                             


2. Then need start process.                                                                                    

                                                                                          ProcessStartInfo processStrInfo = new ProcessStartInfo();
              processStrInfo.FileName =   /// Exe path;
              processStrInfo.Arguments =  /// Parameter to pass as string;
              processStrInfo.UseShellExecute = false;
              Process.Start(processStrInfo);                                                                                                              

3. parameter can send as string.


           string tempCommandArgs ="TestPara";                 


             ProcessStartInfo processStrInfo = new ProcessStartInfo();
             processStrInfo.FileName = "test.exe";  /// Exe path;
             processStrInfo.Arguments = tempCommandArgs  /// Parameter to pass as string;
             processStrInfo.UseShellExecute = false;
             Process.Start(processStrInfo);   

4 .When we passing multiple parameter, we can use space between parameters .


          tempCommandArgs  =COMPANYNAME +" "+USERID

5. If parameter value have spaces.

When a parameter contains spaces—for example, a company name like 'Test Company'—you must wrap the string in double quotes. This ensures the operating system treats the entire phrase as a single argument. In your code, you can achieve this by adding a double-quote character at the start and end of the parameter string."
   
    In this time we can use below method (add stroke to start of parameter and end of parameter)

    tempCommandArgs  ="\"" + COMPANYNAME + "\"" + " "
                                                  +"\"" + USERlOGINNAME. + "\"";    

Note:-
This is way to pass parameter to Exe as argument , But running exe from another running application (exe) is not good practice. It will consume some more memory

Now take a look at how to consume passed argument form exe.

Note:-
This example I have done with WPF application

1. We can override OnStartup in App.xaml.cs

 protected override void OnStartup(StartupEventArgs e)
  {          
            string[] args = Environment.GetCommandLineArgs();
            args = e.Args;
         
            if (args.Count() > 0)
            {            
                COMPANYNAME = args[0];        
                USERNAME = args[1];
            }

 }

Thursday, August 18, 2016

How to convert WPF Application project to Class Library

How do convert WPF Application to Class Library


Let's see how can we convert exist WPF Application project to Class Library project.


  1. Right click on WPF application project and select project properties.
  2. Then select application and change the Out put type to Class Library, save it.
  3. Open App.xaml and remove StartupUri from it.
  4. Then build project, you can see  some error with  the project. so here is the trick to remove error,
  5. Exclude  App.xaml file from project and build project again , it will build project without any errors.
  6. So if you want add App.xaml file to project ,now you can include App.xaml file again.
Note:-
If you going create new project to your solution, you can chose WPF User Control Library or WPF Custom Control Library.





Friday, July 22, 2016

5 Ways to Master Dynamic WHERE Clauses in T-SQL

Stop struggling with complex search filters in your stored procedures. This guide breaks down the most effective techniques for building dynamic WHERE clauses in SQL Server.

  • COALESCE
  • OR Operator
  • ISNULL
  • CASE
  • Dynamic SQL query.
Note - All example I have done with NORTHWIND database

1 . COALESCE.

DECLARE @OrderID int,
                   @ProductID int


SET @OrderID =null
SET @ProductID =null

SELECT [OrderID]
               ,[ProductID]
               ,[UnitPrice]
               ,[Quantity]
               ,[Discount]
FROM [dbo].[OrderDetails]
WHERE OrderID = COALESCE(@OrderID , OrderID)
               AND [ProductID] =COALESCE(@ProductID , [ProductID])

   Find out more about COALESCE

2. OR Operator.

DECLARE @OrderID int,
                   @ProductID int

SET @OrderID =null
SET @ProductID =null

SELECT [OrderID]
                 ,[ProductID]
                 ,[UnitPrice]
                 ,[Quantity]
                 ,[Discount]
FROM    [dbo].[OrderDetails]
WHERE  ((@OrderID IS NULL) OR (OrderID = @OrderID))
                 AND ((@ProductID IS NULL) OR (ProductID =@ProductID))


3. ISNULL.


DECLARE @OrderID int,
                   @ProductID int

SET @OrderID =null
SET @ProductID =null

SELECT [OrderID]
               ,[ProductID]
               ,[UnitPrice]
               ,[Quantity]
               ,[Discount]
 FROM   [dbo].[OrderDetails]
 WHERE OrderID = ISNULL(@OrderID , OrderID)
                AND [ProductID] =ISNULL(@ProductID , [ProductID])

Find out more about ISNULL

4. CASE


 DECLARE @OrderID int,
                    @ProductID int

SET @OrderID =null
SET @ProductID =null

SELECT [OrderID]
             ,[ProductID]
             ,[UnitPrice]
             ,[Quantity]
             ,[Discount]
 FROM [dbo].[OrderDetails]
 WHERE OrderID = CASE WHEN @OrderID IS NOT NULL THEN @OrderID ELSE OrderID                                          END
                                  AND [ProductID] =CASE WHEN @ProductID IS NOT NULL THEN                                                 @ProductID ELSE ProductID END


5. Dynamic SQL Query


DECLARE @OrderID int,
                   @ProductID int ,
                   @DyWhere nvarchar(MAX),
                   @DyQuery nvarchar(MAX)

SET @OrderID =10249
SET @ProductID =NULL
SET @DyWhere =' WHERE'

SET @DyQuery ='SELECT [OrderID]
                                             ,[ProductID]
                                             ,[UnitPrice]
                                             ,[Quantity]
                                             ,[Discount]
                                              FROM [dbo].[OrderDetails]'


IF @OrderID IS NOT NULL
BEGIN
   SET @DyWhere =@DyWhere+ ' OrderID ='+CONVERT(nvarchar, @OrderID)
 
END

IF @ProductID IS NOT NULL
BEGIN
SET @DyWhere =@DyWhere + ' AND ProductID ='+CONVERT(nvarchar, @ProductID)
END

IF @OrderID IS NOT NULL OR @ProductID IS NOT NULL
BEGIN
SET @DyQuery =@DyQuery +@DyWhere
END


EXECUTE sp_ExecuteSQL @DyQuery

Find out more about  sp_ExecuteSQL

You can use above mentioned one of method according to your scenario , Last one (dynamic SQL query ) this can use for more dynamic scenarios.