Below is the code that you can use for concatenating all records into one line text:
declare @s nvarchar(max)
select
@s = coalesce(@s + ',' + prod_code, prod_code)
from prod
select @s
Thursday, February 21, 2013
Friday, January 11, 2013
Using dynamic SQL for reporting process
What is the user requirements for the report?
- Lots of criteria on the screen but most of them are optional.
- The final result is a subset of a result.
- User allows to choose different sorting order.
- User allows to choose different grouping.
- The fields in the report was specified by the user at runtime.
Monday, October 22, 2012
Dynamic SQL usage
One of the usefulness about dynamic SQL is for database maintenance. For example, you want to run the maintenance process in the selected databases.
Below is the flow of using dynamic SQL to ease the maintenance:
The reason to have a table to stores your database names:
Below is the flow of using dynamic SQL to ease the maintenance:
- Create a table that stores the database names for your system.
- Declare a cursor and loop through all your database names and match the process number (explain later).
- Generate the dynamic SQL statement to be executed against the selected databases.
- Finally, execute the dynamic SQL.
The reason to have a table to stores your database names:
- You are not interested in all databases stored in sys.databases. You just want to run the script against the selected databases.
- The database name did not follow any convention before you take over the maintenance. In you are handling the database server, then, you should follow a standard naming convention for the database name. This allows you to query the database name from sys.databases.
- You don't want to execute the SQL statement against all your application databases. Only certain databases are going to run script 1 and other databases are going to run script 2, etc.
- db_name nvarchar(255) - this is the database name
- process_1 int - if '1' means run the maintenance stored procedure #1. '0' to ignore.
- process_2 int - if '1' means run the maintenance stored procedure #2.'0' to ignore.
- (other process flag).
Monday, October 15, 2012
Executing dynamic SQL
In MSSQL, it is able to execute dynamic SQL. Meaning, you are allowed to execute the SQL statement that stores in a variable by calling sp_executesql system stored procedure. It compiles the SQL statement at runtime and then execute it. You may also create parameterized SQL statement so that it compiles once and run multiple times (for example, inserting many records within a loop).
Whenever it's possible, try to avoid using the dynamic SQL. This is because each time you are executing the dynamic SQL statement (not within a loop in the stored procedure), it will be recompiled and increase the execution time.
The advantage of implementing this idea will save you from having a permanent table to store the reporting data or data for the current session. Also, it saves you having tuning the SQL statement with complex WHERE clause where some of the conditions were optional.
The following sample code returns all the object ID-s in the database by using the dynamic SQL statement.
declare @sql nvarchar(max)
select @sql = '
declare @tb table ( id int )
insert into @tb (id)
select object_id from sys.objects
select * from @tb
'
exec sp_executesql @sql
I will discuss a bit more in detail in my next article.
Whenever it's possible, try to avoid using the dynamic SQL. This is because each time you are executing the dynamic SQL statement (not within a loop in the stored procedure), it will be recompiled and increase the execution time.
The advantage of implementing this idea will save you from having a permanent table to store the reporting data or data for the current session. Also, it saves you having tuning the SQL statement with complex WHERE clause where some of the conditions were optional.
The following sample code returns all the object ID-s in the database by using the dynamic SQL statement.
declare @sql nvarchar(max)
select @sql = '
declare @tb table ( id int )
insert into @tb (id)
select object_id from sys.objects
select * from @tb
'
exec sp_executesql @sql
I will discuss a bit more in detail in my next article.
Monday, October 8, 2012
Generating "reminder" for the user
In a mid to large scale application, often you need to run scheduled tasks which can be schedule through the SQL Agent. One type of the schedule is to generate reminder or alert for the user. For example, inform the collection department about the overdue invoice.
Below is the strategy to implement this type of process:
For those alert requires immediate attention, you may send the reminder or alert through SMS (short messaging).
Below is the strategy to implement this type of process:
- Create a stored procedures to scan the data.
- In this stored procedure, it contains the business logic about what data will meet the requirement and then generate the reminder record.
- The reminder record will be saved into tb_mail (this table stores the email to be pickup by a C# program).
- Develop a program in the C# application which will send all the emails in tb_mail table.
For those alert requires immediate attention, you may send the reminder or alert through SMS (short messaging).
Monday, October 1, 2012
Benefits of using stored procedure instead of writing codes in C#
Started from my favorite programming language, Visual Basic 6 (that was in 1997), I've been thinking where is the best place to implement the "business rule". After many years of moving the business rules from the the programming language to the database and vice versa, I've finally decided the best place for the business rule is in the stored procedure.
The simplest stored procedure is for SELECT, INSERT, UPDATE and DELETE. Indeed, you can do more than that. Benefits of using the stored procedure:
The simplest stored procedure is for SELECT, INSERT, UPDATE and DELETE. Indeed, you can do more than that. Benefits of using the stored procedure:
- Create audit log when doing any of the CRUD operation.
- Able to implement sophisticated control in what kind of data can be return to caller.
- Easier to enhance/process the records before returning the records.
- Stored procedure has been compiled and it runs faster than the ad-hoc query.
- Able to enhance the stored procedure at anytime.
- You don't have to recompile the application if there are any changes in the rule.
- You don't have to redistribute the application (at client workstation or web server) if there are any changes in the rule.
Thursday, September 27, 2012
Generate a series of number
Below is a way to generate a series of number (10 records where the value starts from 1 to 10) with Common Table Expression (CTE):
with tb (ii)
as (
select
1 ii
union all
select ii + 1
from tb
where ii + 1 <= 10
)
select *
from tb
For the detailed explanation, check this out:
http://www.databasejournal.com/features/mssql/article.php/3502676/Common-Table-Expressions-CTE-on-SQL-2005.htm
When to use it
with tb (ii)
as (
select
1 ii
union all
select ii + 1
from tb
where ii + 1 <= 10
)
select *
from tb
For the detailed explanation, check this out:
http://www.databasejournal.com/features/mssql/article.php/3502676/Common-Table-Expressions-CTE-on-SQL-2005.htm
When to use it
- Use CTE + UNION ALL to generate hierarchical result. For example, you have a discussion forum where it allows the members to post question (a thread) with many replies (many level of sub-threads).
- Reduce re-typing the same SELECT statement especially you are aggregating the data.
Subscribe to:
Posts (Atom)