Affichage des articles dont le libellé est Active questions tagged sql-server - Stack Overflow. Afficher tous les articles
Affichage des articles dont le libellé est Active questions tagged sql-server - Stack Overflow. Afficher tous les articles

samedi 1 août 2015

Design Pattern for Custom Fields in Reporting System

I have assigned a task to create (relatively) simple reporting system. In these system, user will be shown a table result of report. A table has some fields and each field give some part of information to user in each record. My problem however is that each report field will not be declared by developer. It must be declared by user of system. So my reports table are dynamic.

I saw example in 'Data Driven Custom View Engine in ASP.NET MVC' for creaing dynamic forms using Asp.net MVC Framework but I don't know that is appropriate for my system or not.

Update1:

Currently I ended with followind Entity Relationship Diagram: enter image description here

In above diagram, I store every record for report in Report table. Also I store type of report in ReportType. For each field that will be used in report record I will use a ReportFieldValue. Type of fields will be stored in ReportField.

So If I want to add a record to my db first I add a row to Report Table. Then for each added record fields I will add a row to ReportFieldValue table.

However as you may notice, in these approach I must store every field value in char(255). The problem is for fields type like datetime that should not be stored as string. Is there any design pattern or architecture for this type of systems?

Get SQL query from user and run it against SQL Server

I want to develop very small application by C# which get some SQL query from user and execute it against specified SQL Server.

SQL Server and database must specified by user thus every things can change. My problem is user can enter various type of SQL queries, and every king of it should run in its own way.

For example

SELECT * FROM mytable

and

UPDATE mytable 
SET city = "NY" 
WHERE name = "tom"

can not execute in the same way.

I think I need to recognize user query type in my code, Is there any way to recognize it or any better way to run any possible query?

distinct in mssql server

I am trying a SQL query MSSQL server 2005.

select  distinct emp_code , SSN, name
from dbo.employee
where 
    (City = 'Abc') 
    or
    (Country = 'India') 
and Joining_date between getdate()-60 and getdate()

which is returning 76 queries

But if instead I use

select  distinct emp_code
    from dbo.employee
    where 
        (City = 'Abc') 
        or
        (Country = 'India') 
    and Joining_date between getdate()-60 and getdate()

which is returning 73 records.

I understand that in first query Server is returning where all 3 columns are distinct. How should I write the query if I want only distinct emp_code ?

I have tried using group by emp_code but it is throwing an error Please help!

How can I retrieve second last row?

I have a table with many records and I want to know only the record which I have created at second last.

For ex: I have a table customer in which customerID are random numbers.

Now I want to select second last row.

customerID      customer_name   cont_no
---------------------------------------
 7              david sam       5284
 1              shinthol        1
11              lava            12548
 2              thomas          1
 3              peeter          1
 4              magge           1
 5              revas           1
 6              leela           123975

Output row :

customerID      customer_name   cont_no
5               revas           1

I don't want second highest...

I want second last row.

(Could not open a connection to SQL Server) Error when connecting to remote database from asp.net web application hosted on GoDaddy

I'm getting the following error, while trying to connect to a remote database (on other web hosting server) from my asp.net web app hosted on GoDaddy:

[Win32Exception (0x80004005): The network path was not found]

[SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)]
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +5347119

While working locally and running the asp.net through visual studio, connection to the remote database worked fine. But when I published the application to the GoDaddy server, I received the above error.

Connection String:

<add name="Connection2" connectionString="Server=103.21.58.192;Database=databaseName;Uid=user;Password=password;MultipleActiveResultSets=true" providerName="System.Data.SqlClient"/>

SQL table limitation on update command

Is it possible to restrict more than [n] rows of some tables to get effected when running UPDATE command in SQL? Is it fine if instead of table I can put this limit to entire database?

Or any alternate way you can suggest?

Please help.

Thanks,

Variable not passed by reference | ms-sql and php

When I insert a row into my ms-sql server database, I have the following error:

Warning: Variable parameter 3 not passed by reference (prefaced with an &). Variable parameters passed to sqlsrv_prepare or sqlsrv_query should be passed by reference, not by value. For more information, see sqlsrv_prepare or sqlsrv_query in the API Reference section of the product documentation. in C:\...\ImmoToevoegen.php on line 6

The same warning for parameter 1 and 2.

This is my php code:

<?php
if (!empty($_POST['omschrijving']) && !empty($_POST['woningtype']) && !empty($_POST['data'])){
    $oms = $_POST['omschrijving'];
    $type = $_POST['woningtype'];
    $data = json_encode($_POST['data']);

    $prep = sqlsrv_prepare($conn, "insert into Woning(omschrijving, data, typeid) values (?, ?,  ?);", array($oms, $data, $type));
    sqlsrv_execute($prep);

    print "Woning is toegevoegd";
}
?>

<form action="<?php print $_SERVER['PHP_SELF']; ?>" method="POST">
    <!--param 1 "omschrijving"-->
    Omschrijving:
    <textarea name="omschrijving" id="omschrijving" cols="30" rows="10></textarea>

    <!--param 2 "data"-->
    <div>
        wc: <input type="checkbox" name="data[]" value="wc"/><br/>
        cv: <input type="checkbox" name="data[]" value="cv"/><br/>
        boiler: <input type="checkbox" name="data[]" value="boiler"/><br/>
    </div>

    <!--param 3 "woningtype"-->
    <select name="woningtype" id="woningtype">
        <?php
        //code for load data from database
        print "<option value='" . $rij["ID"] . "'>" . $rij["naam"] . "</option>";
        ?>
    </select>
</form>

<?php
sqlsrv_close($conn);
?>

I use like I said php with a ms-sql server database.

What is wrong with my code?
Thanks

500 internal server error in asp.net website

I have two ASP.NET websites hosted on a server and connecting to the SQL database on on different server.

One of the website throwing 500 internal server errors (as custom error mode on in production). I am not sure what is causing these errors. And these errors are random, so I am not able replicate on dev environment. Both website having almost similar functionality but I am facing these errors only in one website. Recently there so many time out errors. So I asked the system admins to check the event log then they said lot of windows updates are pending, so they ran patch and rebooted both application and database servers.

After that I am getting 500 internal errors while going from login to default page in the website but I am sure there nothing wrong with code and these errors not caught in the application_error event in the global ascx file.

Any insights on how to troubleshoot this issue further?

Why I can't reference to WITH expression more than one time?

In MSSQL I can't reference to WITH expression more than one time?

DECLARE @total FLOAT;
WITH cte AS (
  SELECT s.plate, SUM(s.net) AS tonnage
    FROM scale s
    GROUP BY s.plate
)

SELECT @total = SUM(tonnage) / 100 FROM cte;
SELECT t.*, t.tonnage / @total AS percentage FROM cte t;

Table Indexing consideration for SaaS Project

Would be good to hear you guys out about how best to consider the indexing strategy, because the data in these tables may grow tremendously in the time to come. Decided to proceed by storing multi-tenant data in a single table approach. For an example, I have only couple of tables for this discussion.

CREATE TABLE [dbo].[TenantID](
    [TenantID] [smallint] IDENTITY(1,1) NOT NULL,
    [TenantName] [varchar](128) NOT NULL
) 
CREATE TABLE [dbo].[MenuType](
    [MenuTypeID] [int] IDENTITY(1,1) NOT NULL,
    [TenantID] [smallint] NOT NULL,
    [MenuTypeName] [varchar](128) NOT NULL
) 

  • MenuTypeName should be unique for each Tenant. Therefore, I will have a Unique Index on TenantID and MenuTypeName
  • TenantID should be referenced to Tenant table. So, Foreign Key on TenantID.
  • Am still thinking whether I should have Primary Key or just a Clustered Index on MenuTypeID which is an auto-increment column.
  • In future, when the table size grows I should be able to Partition out the data based on TenantID easily to a new database server.

Questions:

  1. Do I really need to define the Primary Key on MenuTypeID because we know SQL Server guarantees incremental seeds. Can I just define a Clustered Index on MenuTypeID.
  2. Define Unique Key on TenantID and MenuTypeName.

Using this approach, I will not have primary key concept in the table design. But, I would like to hear whether am I inviting trouble in future by not having primary key in the tables?

Optimizing LINQ routines

I run a build system. Datawise the simplified description would be that I have Configurations and each config has 0..n Builds. Now builds produce artifacts and some of these are stored on server. What I am doing is writing kind of a rule, that sums all the bytes produced per configuration builds and checks if these are too much.

The code for the routine at the moment is following:

private void CalculateExtendedDiskUsage(IEnumerable<Configuration> allConfigurations)
{
    var sw = new Stopwatch();
    sw.Start();
    // Lets take only confs that have been updated within last 7 days
    var items = allConfigurations.AsParallel().Where(x =>
        x.artifact_cleanup_type != null && x.build_cleanup_type != null &&
        x.updated_date > DateTime.UtcNow.AddDays(-7)
        ).ToList();

    using (var ctx = new LocalEntities())
    {
        Debug.WriteLine("Context: " + sw.Elapsed);
        var allBuilds = ctx.Builds;
        var ruleResult = new List<Notification>();
        foreach (var configuration in items)
        {
            // all builds for current configuration
            var configurationBuilds = allBuilds.Where(x => x.configuration_id == configuration.configuration_id)
                .OrderByDescending(z => z.build_date);
            Debug.WriteLine("Filter conf builds: " + sw.Elapsed);

            // Since I don't know which builds/artifacts have been cleaned up, calculate it manually
            if (configuration.build_cleanup_count != null)
            {
                var buildCleanupCount = "30"; // default
                if (configuration.build_cleanup_type.Equals("ReserveBuildsByDays"))
                {
                    var buildLastCleanupDate = DateTime.UtcNow.AddDays(-int.Parse(buildCleanupCount));
                    configurationBuilds = configurationBuilds.Where(x => x.build_date > buildLastCleanupDate)
                            .OrderByDescending(z => z.build_date);
                }
                if (configuration.build_cleanup_type.Equals("ReserveBuildsByCount"))
                {
                    var buildLastCleanupCount = int.Parse(buildCleanupCount);
                    configurationBuilds =
                        configurationBuilds.Take(buildLastCleanupCount).OrderByDescending(z => z.build_date);
                }
            }

            if (configuration.artifact_cleanup_count != null)
            {
                // skipped, similar to previous block
            }

            Debug.WriteLine("Done cleanup: " + sw.Elapsed);
            const int maxDiscAllocationPerConfiguration = 1000000000; // 1GB
            // Sum all disc usage per configuration
            var confDiscSizePerConfiguration = configurationBuilds
                .GroupBy(c => new {c.configuration_id})
                .Where(c => (c.Sum(z => z.artifact_dir_size) > maxDiscAllocationPerConfiguration))
                .Select(groupedBuilds =>
                    new
                    {
                        configurationId = groupedBuilds.FirstOrDefault().configuration_id,
                        configurationPath = groupedBuilds.FirstOrDefault().configuration_path,
                        Total = groupedBuilds.Sum(c => c.artifact_dir_size),
                        Average = groupedBuilds.Average(c => c.artifact_dir_size)
                    }).ToList();
            Debug.WriteLine("Done db query: " + sw.Elapsed);

            ruleResult.AddRange(confDiscSizePerConfiguration.Select(iter => new Notification
            {
                ConfigurationId = iter.configurationId,
                CreatedDate = DateTime.UtcNow,
                RuleType = (int) RulesEnum.TooMuchDisc,
                ConfigrationPath = iter.configurationPath
            }));
            Debug.WriteLine("Finished loop: " + sw.Elapsed);
        }
        // find owners and insert...
    }
}

This does exactly what I want, but I am thinking if I could make it any faster. Currenly I see:

Context: 00:00:00.0609067
// first round
Filter conf builds: 00:00:00.0636291
Done cleanup: 00:00:00.0644505
Done db query: 00:00:00.3050122
Finished loop: 00:00:00.3062711
// avg round
Filter conf builds: 00:00:00.0001707
Done cleanup: 00:00:00.0006343
Done db query: 00:00:00.0760567
Finished loop: 00:00:00.0773370

The SQL generated by .ToList() looks very messy. (Everything that is used in WHERE is covered with an index in DB)

I am testing with 200 configurations, so this adds up to 00:00:18.6326722. I have a total of ~8k items that need to get processed daily (so the whole routine takes more than 10 minutes to complete).

I have been randomly googling around this internet and it seems to me that Entitiy Framework is not very good with parallel processing. Knowing that I still decided to give this async/await approch a try (First time a tried it, so sorry for any nonsense).

Basically if I move all the processing out of scope like:

        foreach (var configuration in items)
        {

            var confDiscSizePerConfiguration = await GetData(configuration, allBuilds);

            ruleResult.AddRange(confDiscSizePerConfiguration.Select(iter => new Notification
            {
               ... skiped
        } 

And:

private async Task<List<Tmp>> GetData(Configuration configuration, IQueryable<Build> allBuilds)
        {
                var configurationBuilds = allBuilds.Where(x => x.configuration_id == configuration.configuration_id)
                    .OrderByDescending(z => z.build_date);
                //..skipped
                var confDiscSizePerConfiguration = configurationBuilds
                    .GroupBy(c => new {c.configuration_id})
                    .Where(c => (c.Sum(z => z.artifact_dir_size) > maxDiscAllocationPerConfiguration))
                    .Select(groupedBuilds =>
                        new Tmp
                        {
                            ConfigurationId = groupedBuilds.FirstOrDefault().configuration_id,
                            ConfigurationPath = groupedBuilds.FirstOrDefault().configuration_path,
                            Total = groupedBuilds.Sum(c => c.artifact_dir_size),
                            Average = groupedBuilds.Average(c => c.artifact_dir_size)
                        }).ToListAsync();
            return await confDiscSizePerConfiguration;
    }

This, for some reason, drops the execution time for 200 items from 18 -> 13 sec. Anyway, from what I understand, since I am awaiting each .ToListAsync(), it is still processed in sequence, is that correct?

So the "can't process in parallel" claim starts coming out when I replace the foreach (var configuration in items) with Parallel.ForEach(items, async configuration =>. Doing this change results in:

A second operation started on this context before a previous asynchronous operation completed. Use 'await' to ensure that any asynchronous operations have completed before calling another method on this context. Any instance members are not guaranteed to be thread safe.

It was a bit confusing to me at first as I await practically in every place where the compiler allows it, but possibly the data gets seeded to fast.

I tried to overcome this by being less greedy and added the new ParallelOptions {MaxDegreeOfParallelism = 4} to that parallel loop, peasant assumption was that default connection pool size is 100, all I want to use is 4, should be plenty. But it still fails.

I have also tried to create new DbContexts inside the GetData method, but it still fails. If I remember correctly (can't test now), I got

Underlying connection failed to open

What possibilities there are to make this routine go faster?

Not able to insert values in mysql using C and Linux

I have created a client server program and using sql in it for the first time. I am getting issues in the sql. to create table i have used the following command

char nsds_table_cmd[]="DROP TABLE IF EXISTS NSDS_TABLE; CREATE TABLE NSDS_TABLE(ID BIGINT, nguid VARCHAR(16),MAC CHARACTER(6), MACHINE_TYPE SMALLINT, STATE SMALLINT, \
                         REGISTERED_HOST TEXT, TIME TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,PRIMARY KEY(ID,MACHINE_TYPE))";
char nsds_database_cmd[]="DROP DATABASE IF EXISTS nsdsDB; CREATE DATABASE nsdsDB";

I have created a struct whose object i am passing to my function that insert into the table

typedef struct nsds_entry {
        long int client_id;
        char nguid[nguid_len];
        char mac[mac_len];
#if 0
        char function_id;
        unsigned int controller_id;
#endif 
        short int client_type;
        short int current_state;
        long int registered_host;
}__attribute__ ((packed)) sql_cmd;

In server when i receive a packet from the client which have the following values

 Destination_address = FF-FF-FF-FF-FF-FF 
    Source_address      = 00-00-00-00-00-00
    Ether_type          = 9998
    Packet_type         = 3
    ACK_type            = 0
    Client_type         = 2
    Client_mac          = 00-00-00-00-00-00 
    Server_mac          = 00-00-00-00-00-00 
    HSID                = 01-02-03-04-AB-CD-EF-AC
    Client_nguid        = 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
    EOPS                = ffff0000

i am filling the nsds_entry struct like this

   LOG_INFO("Ack packet transmission successful\n");
    memcpy(g_sql_obj.client_id,ack->client_id,NVMAR_HSID_LEN);
    memcpy(&g_sql_obj.mac,ack->client_mac, NVMAR_MAC_LEN);
    LOG_INFO("ack_tx client_mac = %s\n",g_sql_obj.mac); // this dosen't print i mean no value as shown in output below
    LOG_INFO("ack_tx:   Client_mac        = %.2X-%.2X-%.2X-%.2X-%.2X-%.2X\n", g_sql_obj.mac[0], g_sql_obj.mac[1],
                                                    g_sql_obj.mac[2], g_sql_obj.mac[3], g_sql_obj.mac[4], g_sql_obj.mac[5]); // this prints exactly the value we copied
    memcpy(g_sql_obj.nguid,ack->client_nguid,NVMAR_NGUID_LEN);
    LOG_INFO("ack_tx:   Client_nguid        = %.2X-%.2X-%.2X-%.2X-%.2X-%.2X-%.2X-%.2X-%.2X-%.2X-%.2X-%.2X-%.2X-%.2X-%.2X-%.2X\n", g_sql_obj.nguid[0], g_sql_obj.nguid[1],
                                                    g_sql_obj.nguid[2], g_sql_obj.nguid[3], g_sql_obj.nguid[4], g_sql_obj.nguid[5],
                                                    g_sql_obj.nguid[6], g_sql_obj.nguid[7], g_sql_obj.nguid[8], g_sql_obj.nguid[9],
                                                    g_sql_obj.nguid[10], g_sql_obj.nguid[11], g_sql_obj.nguid[12], g_sql_obj.nguid[13],
                                                    g_sql_obj.nguid[14], g_sql_obj.nguid[15]);


    g_sql_obj.client_type = htons(ack->client_type);
    g_sql_obj.current_state = NVMAR_STATE_ACTIVE;
    g_sql_obj.registered_host = 0xffffffff;


 nvmar_db_sql_insert_into_table(&g_sql_obj);


Output are as follows

ack_tx:832:ack_tx:   Client_mac        =
ack_tx:832:ack_tx:   Client_mac        = 00-00-00-00-00-00
ack_tx:838:ack_tx:   Client_nguid        = 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00


unsigned int nvmar_db_sql_insert_into_table(struct nsds_entry *row)
{

    char cmd[buffer_l];

    sprintf(cmd,"%s%ld,'%s','%s',%x,%x,'%lx,',%s","INSERT INTO NSDS_TABLE VALUES(",row->client_id,row->nguid,row->mac,row->client_type,row->current_state,row->registered_host,"NULL)");//original

        if (mysql_query(g_db_ctxt.db_handle.nsds, cmd)) {
        finish_with_error(g_db_ctxt.db_handle.nsds);
    }

    return 1;
}

What i need is when i use the following command in sql "select * from table_name" client_mac should be seen as 00-00-00-00-00-00 not in hex, i mean all value should be seen as above

I know that in creating cmd i am not getting any value for the mac and nguid fields as i am reading them through %s but what is the solution. Do i have to change my table definition?

How do I put a SQL Server database under version control using Visual Studio Community 2015 RC?

I would like to put my database schema and its data in my git repository and have it version controlled, just like my code.

I have SQL Server 2008 R2 and Visual Studio Community 2015 RC. I know that Visual Studio 2010 upwards, Database project templates have been introduced to do just this. Please see this article for example. But I don't find those templates in my Visual Studio Community Edition 2015 RC installation.

Saving the normal(dont have any login permission to application) and admin users data in same tables is a good design

I am designing the vehicle management database and created tables USERS and USER-ROlE,ROLES for the admin and other users who has the access to create permissions.Now the question is can i save the vehicle operator data alos in the same tables is it good design?

run migration script in disconnected mode in sql server

can I run migration script in disconnected mode or when connection disconnect than it can be start from last stop. my migration script is taking approx. 2 hrs ,because there are too much data and lots of logics.when we start migration one to another database by this script, than sometimes connection disconnected or light off etc. problems..than data rollback automatically , so I want that when sql disconnect or light off than can we stop migration and when it comes in connected mode,it will start from last stop..is it possible ???

SQL Server 2008 dbms and Visual Studio

I need to add one more column in gridview as difference of Supplier_Quantity - Store_quantity and that difference should store in new column after the supplier_Quantity when I click on Calculate button column what should I do?

I try the following query

select 
    Product_Name, Supplier_Quantity, Store_Quantity,
    'DIFFRENCE' = Supplier_Quantity - Store_Quantity 
from 
    relatesupp

but it shows in sql only and as soon as I use it in Visual Studio it doesn't show in gridview.

Inserting large amount of data (5k rows) from one table to another shuffles rows in SQL Server

I use SQL Sserver 2008.

While inserting large amount of data (about 5k rows) from one table to another shuffles rows. This happens only few times, not always. I have also used Order by clause to order the rows.

Is this possible?

The query is shown here:

INSERT INTO R_G_23 (Sr_No, Date, Item_Code, Item_Name, Received_Qty, Invoice_No, Invoice_Date, Supplier_ECC_No, Supplier_Name, Supplier_Address, Range_and_Division, Issued_Challan_No, Issued_Date, Issued_Qty, Ar_In_No_Date, Qty,Doc_Part, Otherwise_Qty, Balance_Qty, Excise_Officer_Initial, GRN_No)
   SELECT 
       Sr_No, Date, Item_Code, Item_Name, Received_Qty, Invoice_No, Invoice_Date, Supplier_ECC_No, Supplier_Name, Supplier_Address, Range_and_Division, Issued_Challan_No, Issued_Date, Issued_Qty, Ar_In_No_Date, Qty,Doc_Part, Otherwise_Qty, Balance_Qty, Excise_Officer_Initial, GRN_No
   FROM 
       Temp_R_G_23 
   ORDER BY 
       Sr_No asc;

vendredi 31 juillet 2015

Not able to start sql server service after moving the data files to new location

I have moved the data files to new location but while moving I have given the wrong data file name. So it is throwing error

A file activation error occurred. The physical file name 'D:\Programfiles\Microsoft Sql server\MSSQL2008\Data\MSDBLog.ldf' may be incorrect. Diagnose and correct additional errors, and retry the operation.

FCB::Open failed: Could not open file D:\Programfiles\Microsoft Sql server\MSSQL2008\Data\modellog.ldf for file number 2. OS error: 5(Access is denied.).

these were the errors I was getting after the data file movement.

Please suggest me what should be done to run the sql server service.

How to check srttotime value and database value in laravel

Hi I have table wys_attendances(id,t_id, t_date,t_month_t_year,t_attend)

Iam trying to fetch one full month attendances from wys_attendance table like pivot table format. rows base teacher name and column base full month day (1/2/2015,2/2/2015....28/2/2015) i got this format output by using this code my controller $teacher = WysTeacher::all(); $dayCount = date('t', strtotime('01-'. $amonth . '-' . $ayear)); for($i = 1; $i <= $dayCount; $i++)

my view .blade.php

<tr class="tbl-head"> <td>Teacher Name</td> @for($i = 1; $i <= $dayCount; $i++) <td>{{$i}}</td> @endfor </tr> @foreach($teacher as $teachers) <tr>
<td>{{$teachers->tname}}</td> @endforeach </tr>

then iam try to display attendance(present() p/absend(a))below in column date and also corrseponding teachername by usinf this code

@foreach($attendance as $attendances)
                  @if($teachers->id == $attendances->t_auserid)  
                  @if($attendances->t_attendance == 1)
                  <td><font color="green">p</font></td>
                  @elseif($attendances->t_attendance == 0)
                  <td><font color="red">a</font></td>    
                  @endif
                  @endif
 @endforeach

its work fine ,but one problem ,the problem is attendance marked at not corresponding date.

if1/2/2015 date not in database and 2.2/2015 is in database all present(p). but display in view page column 1/2/2015 below marked p value and 2/2/2015 below marked next day attendance .

how to check month date and database value is correct??and display attendance at correcponding date below.

Single Select SQL Statement for 2 different Values

I have a SQL Server table with a column called Category. In my user interface, I have a dropdown list of the category. User can select a category and click on a Search button to filter the results by the category. In the dropdown, the first option is blank. Means if the user wants to see all records from all categories, he can select blank.

In my SQL Select I have 2 statements for this

IF @Catg IS NULL
Begin
    Select * 
    From Table
End
Else
Begin
    Select * 
    From Table 
    Where Catg = @Catg
End

The Catg column in the table will have either a NULL or a category. Is this possible to do in a single SQL statement?