Search This Blog

Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

Wednesday, January 06, 2010

Data access optimization steps in SQL Server


Use Indexing
  • Apply proper indexing in the table columns in the database
    • Make sure that every table in your database has a primary key.
    • Create non-clustered indexes on columns which are, frequently used in the search criteria, Used to join other tables, Used as foreign key fields , Of having high selectivity (Column which returns a low percentage (0-5%) of rows from a total number of rows on a particular value) or Used in the ORDER BY clause
  • Create appropriate covering indexes
    • Use Database Tuning Advisor’s help while creating covered index
  • Defragment indexes if fragmentation occurs
It's really tempting to create index on all eligible columns in your database tables. But, if you are working with a transactional database (An OLTP system where update operations take place most of the times), creating indexes on all eligible columns might not be desirable every time. In fact, creating heavy indexing on OLTP systems might reduce overall database performance (As most operations are update operations, updating data means updating indexes as well).

A rule of thumb can be suggested as follows: If you work on a transactional database, you should not create more than 5 indexes on the tables on an average. On the other hand, if you work on a Data warehouse application, you should be able to create up to 10 indexes on the tables on an average.



Re-factor TSQLs and apply best practices
  • Move TSQL codes from application into the database server
  • Identify inefficient TSQLs, re-factor and apply best practices
    • Don’t use “SELECT*" in SQL Query
    • Avoid unnecessary columns in SELECT list and unnecessary tables in join conditions
    • Do not use the COUNT() aggregate in a subquery to do an existence check
    • Try to avoid joining between two types of columns
    • Try to avoid deadlocks 
    • Write TSQLs using “Set based approach” rather than using “Procedural approach” 
    • Try not to use COUNT(*) to obtain the record count in the table 
    • Try to avoid dynamic SQLs
    • Try to avoid the use of Temporary Tables, try to use Table variables.
    • Instead of LIKE search, Use Full Text Search for searching textual data 
    • Try to use UNION to implement “OR” operation 
    • Use VARCHAR(MAX), VARBINARY(MAX) and NVARCHAR(MAX) 
    • Do not call functions repeatedly within your stored procedures, triggers, functions and batches.
    • Try to avoid the use of triggers.
    • Try to avoid nested transaction.
    • Understanding the query execution plan
    • Getting rid of the unnecessary Text column in the SELECT list
Apply advanced indexing and denormalization
  • Apply some advanced indexing techniques
    • Implement computed columns and create index on these
    • Create "Indexed Views"
    • Create indexes on User Defined Functions (UDF), using computed columns
    • Create indexes on XML columns
  • Apply de-normalizations, use history tables and pre-calculated columns
Diagnose database performance problems
  • Diagnose performance problem, use SQL Profiler and Performance Monitoring tool effectively.
Optimize database files and apply partitioning
  • Organize the file groups and files in the database
  • Apply partitioning in the big fat tables


Original Source: M.M.Al-Farooque Shubho

Thursday, December 18, 2008

Importance of CSS in web development

CSS style sheets have made it easier to handle web pages during web development. CSS or Cascading Style Sheets as the name suggests is a style sheet that allows you to easily link to other documents in your website. It allows you to retain control over the various elements in different web pages of your website.

CSS only defines the structure and content presentation of a website it has nothing to do with the design of a website. A single CSS sheet can control the font, positioning, colour and style information of an entire website.

9 advantages of using CSS
* Web pages are easier to load and uses less bandwidth
CSS style sheets are preferred by web developers for website development because they are lighter than table layouts, which consumes lots of bandwidth. The style sheet is downloaded only once and stored in the cache memory, so subsequent pages load faster.

* A CSS style sheet compliments well with HTML
HTML is insufficient when used independently in website development, but when combined with CSS they can result in technically stronger web pages.

* CSS allows you to position your element anywhere in the webpage
Web developers love to use CSS because it allows them to position their element where ever they want in the web page. If during any phase of web development the developer feels that particular links or columns are not going well with the situation then it becomes easier for them to position them easily using CSS. CSS reduces the risks associated with maintenance of the website.

* CSS is compatible with all web browsers
CSS is combined with HTML or XHTML by web developers for web application development because it is compatible with all web browsers. The sites that use CSS appear similar in all the web browsers.

* CSS can be used to create print friendly web pages
Most of the web developers love to use CSS for building their HTML based web applications because they allow them to create print friendly web pages. These web pages can be easily printed. The colours, images and other things which are difficult to be printed can be eliminated and printed easily.

* CSS style sheets allows the user to customize the webpage
Now days many websites allow the user to change the layout of the website without affecting the content. The CSS style sheets which are stored externally allow the user to make requisite changes by themselves. Most of the modern browsers give user the liberty to define their own style sheets like changing some font properties etc.

* CSS style sheets makes it easier for your website to feature in search engines
The CSS style sheets are favoured by web developers because they allow them to position their elements as per their wish anywhere in web application. Positioning helps to project the main contents first, so that it is easily captured by web spiders. CSS also gives cleaner HTML codes thus cutting down the job of web spider to search the real content from junk code.

* CSS allows the web pages to have absolute consistency
One of the reasons for using CSS during web development is that they allow consistency to all web pages. All the expressions and texts will get their characteristics from external style sheet. Web developers need not to worry about the change in characteristics of the elements because they can be easily altered at any stage of web development by using CSS.

* CSS lends portability to content
By using CSS you can make separate style sheets for different media. This provides you the great flexibility in presenting your content. CSS allows you to redefine the characteristics of elements in a website to suit the need of the situation. For e.g.: A separate style sheet will allow you to redefine the characteristics of certain elements so that they are easier to be printed. Also the user will never come to know that you had restructured the characteristics for their benefit.

CSS is created to make the things easier for your website and also to give you control over different elements in your website. Utilizing benefits of CSS will give you popular user friendly web pages.

To appreciate the beauty and flexibility of CSS, check out the site, CSSZenGarden.com
The Zen Garden aims to excite, inspire, and encourage participation. To begin, view some of the existing designs in the list. Clicking on any one will load the style sheet into this very page. The code remains the same, the only thing that has changed is the external .css file.

CSS allows complete and total control over the style of a hypertext document. The only way this can be illustrated in a way that gets people excited is by demonstrating what it can truly be, once the reins are placed in the hands of those able to create beauty from structure. To date, most examples of neat tricks and hacks have been demonstrated by structurists and coders. Designers have yet to make their mark. This needs to change.

Original Source:
http://support.fuchsiasoft.org/importance-of-css-in-web-development-t67.html

Saturday, February 09, 2008

SQL Injection

SQL injection is a technique that exploits a security vulnerability occurring in the database layer of an application. The vulnerability is present when user input is either incorrectly filtered for string literal escape characters embedded in SQL statements or user input is not strongly typed and thereby unexpectedly executed. It is in fact an instance of a more general class of vulnerabilities that can occur whenever one programming or scripting language is embedded inside another.

SQL Injection: A Simple Example
Take a simple login page where a legitimate user would enter his username and password combination to enter a secure area to view his personal details or upload his comments in a forum.

When the legitimate user submits his details, an SQL query is generated from these details and submitted to the database for verification. If valid, the user is allowed access. In other words, the web application that controls the login page will communicate with the database through a series of planned commands so as to verify the username and password combination. On verification, the legitimate user is granted appropriate access.

Through SQL Injection, the hacker may input specifically crafted SQL commands with the intent of bypassing the login form barrier and seeing what lies behind it. This is only possible if the inputs are not properly sanitized (i.e., made invulnerable) and sent directly with the SQL query to the database. SQL Injection vulnerabilities provide the means for a hacker to communicate directly to the database.

The technologies vulnerable to this attack are dynamic script languages including ASP, ASP.NET, PHP, JSP, and CGI. All an attacker needs to perform an SQL Injection hacking attack is a web browser, knowledge of SQL queries and creative guess work to important table and field names. The sheer simplicity of SQL Injection has fueled its popularity.

Forms of SQL injection vulnerabilities
Incorrectly filtered escape characters
This form of SQL injection occurs when user input is not filtered for escape characters and is then passed into a SQL statement. This results in the potential manipulation of the statements performed on the database by the end user of the application.

Incorrect type handling
This form of SQL injection occurs when a user supplied field is not strongly typed or is not checked for type constraints. This could take place when a numeric field is to be used in a SQL statement, but the programmer makes no checks to validate that the user supplied input is numeric.

Blind SQL Injection
Blind SQL Injection is used when a web application is vulnerable to SQL injection but the results of the injection are not visible to the attacker. The page with the vulnerability may not be one that displays data but will display differently depending on the results of a logical statement injected into the legitimate SQL statement called for that page. This type of attack can become time-intensive because a new statement must be crafted for each byte recovered. A tool called Absinthe can automate these attacks once the location of the vulnerability and the target information has been established.

Preventing SQL Injection
To protect against SQL injection, user input must not directly be embedded in SQL statements. Instead, user input must be escaped, or parameterized statements must be used.

Using Parameterized Statements
Parameterized statements use parameters (sometimes called placeholders or bind variables) instead of embedding user input in the statement. In many cases, the SQL statement is fixed. The user input is then assigned (bound) to a parameter.

Enforcing the Use of Parameterized Statements
There are two ways to ensure an application is not vulnerable to SQL injection: using code reviews (which is a manual process), and enforcing the use of parameterized statements. Enforcing the use of parameterized statements means that SQL statements with embedded user input is rejected at runtime.

How to check for SQL injection vulnerabilities
Securing your website and web applications from SQL Injection involves a three-part process:

   1. Analysing the present state of security present by performing a thorough audit of your website and web applications for SQL Injection and other hacking vulnerabilities.
   2. Making sure that you use coding best practice sanitizing your web applications and all other components of your IT infrastructure.
   3. Regularly performing a web security audit after each change and addition to your web components.

Furthermore, the principles you need to keep in mind when checking for SQL Injection and all other hacking techniques are the following: “Which parts of a website we thought are secure are open to hack attacks?” and “what data can we throw at an application to cause it to perform something it shouldn’t do?”.

Checking for SQL Injection vulnerabilities involves auditing your website and web applications. Manual vulnerability auditing is complex and very time-consuming. It also demands a high-level of expertise and the ability to keep track of considerable volumes of code and of all the latest tricks of the hacker’s ‘trade’.

The best way to check whether your web site and applications are vulnerable to SQL injection attacks is by using an automated and heuristic web vulnerability scanner.

An automated web vulnerability scanner crawls your entire website and should automatically check for vulnerabilities to SQL Injection attacks. It will indicate which URLs/scripts are vulnerable to SQL injection so that you can immediately fix the code. Besides SQL injection vulnerabilities a web application scanner will also check for Cross site scripting and other web vulnerabilities.

Resources:
  • http://en.wikipedia.org/wiki/SQL_injection
  • http://www.unixwiz.net/techtips/sql-injection.html
  • http://www.acunetix.com/websitesecurity/sql-injection.htm
  • http://ferruh.mavituna.com/sql-injection-cheatsheet-oku/
  • http://www.acunetix.com/websitesecurity/sql-injection2.htm

Friday, August 31, 2007

Optimize your Web site performance to survive heavy traffic

1. Avoid accessing databases to often
On a database driven content sites, the slowest task is accessing the database to retrieve the content to display. If a site is not fast enough to serve its pages, many simultaneous user accesses force the Web server to create more processes to handle all the requests.
This is bad because it demands more server memory. Once the server RAM is exhausted, the machine starts using the virtual memory, making the server even slower, until it halts completely.

2. Cache Web pages
If the site needs to access the database to retrieve the content to display, what can we do to minimize the database accesses?
First, we need to focus on what kind of information the site retrieves from databases. The most common type of data is information used to build the HTML pages.
The fact is that the information in database does not change so frequently. As a matter of fact, usually different users see the exact same HTML content when they access the same page.
It is not unusual to execute many SQL queries to retrieve all the data that is necessary to build a single HTML page. So, it is evident that it would be much more efficient if the sites could cache the HTML of each page after it is accessed for the first time.
So, what if the database content changes? Just call a code that invalidates all the page caches that depend on content of the changed database table rows. This way, it forces the caches to be rebuilt on the next access to the site pages, and so the pages are always upto date.

3. Avoid needless personalization
What about pages that appear differently to each user that accesses them? Use separate cache files depending on the user accessing the pages.
However, it would useless if the site would use a separate cache file to store the HTML that each user sees. The benefit of reusing cached information would be lost.
To maximize the efficiency of this approach you should minimize the number of user profiles that may be used for each page context. Therefore, it is very important to avoid personalization as much as you can.

4. Queue tasks that may take too long
Caching is great to avoid repeated accesses to the same content stored in a database.
However, caching only applies to accesses that retrieve data from databases. Operations that update the database content may not benefit from caching. However, when done to frequently, database write accesses may cause server overload.
One of the solution is not to update that table in real time. Instead, create a similar table that act as a queue. The queue table has no indexes. Periodically, start a background task from cron, and move the queue table data to the main table.

5. YSlow 13 optimization rules
There are many aspects to be concerned regarding what to do to make browsers interact with the Web servers in an optimized way that it takes less time and less server resources.
The issues are often not trivial to understand for people looking for quick and easy solutions to optimize their Web sites. Fortunately, there are tools that help you to audit your sites and suggest what needs to be done to boost the performance of the sites to the limit.

YSlow is one of those Web site performance auditing tools. This is a tool that the fine folks of the team of Jeremy Zawodny at Yahoo! released a few weeks ago.
http://developer.yahoo.com/yslow/

This is a wonderful tool that in a few seconds gives you an overview of how a page of your site is being served. It also suggests what can be done to optimize aspects that affect page loading speed and the consumption of Web server resources.
This tool is an extension for the Firefox browser. It works together with another very good extension named Firebug. So, to use YSlow, first you need to install Firebug.
http://www.getfirebug.com/

Once you have installed Firebug and YSlow, it is very easy to audit the performance of any Web page. Just load a Web page that you want to test and wait until it finishes loading. Then open the Firebug pane, click on the YSlow tab, and use the Performance button.

Immediately YSlow starts collecting details about the current page. When it is done it shows a list of 13 rules about aspects of the page loading performance.
On the left side of the listing you see grades from A to F. Those grades express how your page performs on each of the 13 rules, A being the best and F being the worst. On the top of the listing you see your overall "Performance Grade" also from A to F, and a score between 0 and 100.
If you got the score 100, congratulations, your page is perfect. Otherwise there is performance tuning work to be done.

Thirteen Simple Rules for Speeding Up Your Web Site are
  1. Make Fewer HTTP Requests
  2. Use a Content Delivery Network
  3. Add an Expires Header
  4. Gzip Components
  5. Put Stylesheets at the Top
  6. Put Scripts at the Bottom
  7. Avoid CSS Expressions
  8. Make JavaScript and CSS External
  9. Reduce DNS Lookups
  10. Minify JavaScript
  11. Avoid Redirects
  12. Remove Duplicate Scripts
  13. Configure ETags


6. Too much AJAX and external Javascript may kill your page performance
Using AJAX and cool Javascript libraries is definitely the latest fashion in Web application development. These are common aspects that you may notice in the so-called Web 2.0 sites.
The problem is that when you use a Javascript library that has may interdependent components, sometimes to use a simple component you end up loading a pile of separate Javascript files.

This makes the browser send a lot of requests to the Web server once it enters a page that needs many of those Javascript files. Not only it may cause excessive load to the server, but it also slows down the rendering of a page, even when the page HTML has already been fully loaded. It is a similar effect of pages that use Flash movies that take a while to load.

Browsers cache Javascript files, but when the user is making the first access to a page that needs many Javascript files, it may take too long. It may give the impression that your site is much slower than it actually is.

More detailed information regarding rules to optimize your Web site performance and for defensive programming practices to survive Web site traffic peaks can be found in www.phpclasses.org

Wednesday, August 22, 2007

Work Place Stress

Stress is one of those things that no one likes to admit to feeling, and definitely it's rare for anyone to admin to having trouble dealing with stress. Part of this is pride and stubbornness of course, but I think just as often it's because the person doesn't believe they are under stress. Not denial, but lack of recognition. Stress can come from many things, big and small. Traffic jams, long hours at work, sick kids, newspaper not being delivered, death of a loved one.

I think part of that lack of recognition is that many stress causing items get lumped into one of these categories; annoying, irritating, worrisome, nagging. Whether or not something goes from irritating to stressful depends on your state of mind (stress level if you will) and your natural defenses against that particular kind of stress. For example, all of the items below are types of things that will happen to most employees at some point in their career. Probably there are some that would stress you right now, rumors of layoffs for example. Maybe others used to be stressful - deadlines perhaps - but you've gotten used to them and now they no longer have a negative impact on you. Perhaps still others are never stressful. Sometimes it's the combination - you're working long hours to meet a tough but fair deadline, you're going to a lot of meetings that seem to have no purpose, a co-worker is complaining in your ear constantly, and you just got dinged in a code review for not coding defensively enough. Can you see how all those little things might add up to real stress?

Office stress points:

  • Deadlines (not just unreasonable ones)
  • Rumors of layoffs or offshoring
  • Meetings that seem to have no purpose
  • Co-worker constantly complaining (or on the phone with spouse, or ...)
  • Annual review
  • Co-worker not pulling their weight
  • New employee that seems to have skills/experience far exceeding your own, or that seems to have very poor skills
  • New manager
  • Code reviews
  • Dressing up for/entertaining clients
  • Working long hours/weekends
  • Lack of cooperation from other departments
  • Poor leadership at any level
  • Company in financial trouble

 

It's important to say that you cannot avoid all stress, and that some stress is probably even helpful at times (deadlines for example have a way of focusing you and getting you to exclude all the 'extras' from your schedule until the goal is met). What you can do is challenge yourself to think about your reaction to stress and to be mindful that things are causing you stress. Before we explore that more, let's talk about what I consider the primary types of reactions to stressful situations:

  • Individual does not feel stress from the situation, due to experience and/or outlook on life. Note that this is NOT ignoring it, it truly is not perceived as stressful
  • Individual denies the stress and it's impact on their mental state.
  • Individual acknowledges the stress and tries to manage it

How can you get to the point where something is not stressful? Let's take rumors of layoffs for example. Suppose you've only been at the company for a year, your wife is pregnant, and you basically live paycheck to paycheck, putting you in the high risk of being let go category and being at risk financially if you're out of work very long. What steps could you take to reduce your stress level? Potentially you could:

  • Realize that not all rumors work out to be true, sit down with your manager to try to find out more about the situation
  • Understand that companies usually lay off the bottom tier of employees first, the marginal performers. Make sure you're not in that category. Note that maintaining a good attitude can also keep you out of the first group to go.
  • Update your resume, check with friends about possible opportunities with other companies, even reach out to your favorite recruiter. You want to be prepared to job hunt if you have to, and you want to know the state of the job market.
  • Cut back on your spending to try to build a little more financial cushion (note that this also helps in case they do salary cuts instead of layoffs)
  • Arrange a line of credit on your house in case you need money if you wind up out of work
  • If you are laid off, be ready to try to negotiate a severance package that will help you - in this case maybe getting them to cover your insurance for a longer period of time
  • I'm not advocating jumping ship, but that is one way to remove the stress altogether. The problem is that many times the rumors are just rumors, and you start all over again at another company when you didn't have to. You also risk having your current employer finding out that you're looking in response to rumors, which may well guarantee you're on the gotta go list

If you were to do all those things, maybe your stress level drops from an 8 to a 5. Odds are you aren't going to feel stress free, but you should feel better and you've taken logical steps in case the rumor is true. How can anyone hear about layoffs and not feel stressed? Imagine that you've been with the company ten years, you've got a strong financial reserve, you're a star employee that is highly trusted and respected, you've got superb technical skills, and you've survived layoffs at this company twice before. The worst is that you have to look for a new job and that doesn't cause any fear because you have money (which equals time to find a good job) and you have marketable skills.

There are two patterns I try to use. The first is 'immediate stress'. When I feel something causing me stress, I try to take the following steps - writing down the answers:

  • In a couple sentences, what is bothering me?
  • Is my reaction to this emotional or logical?
  • Is my reaction proportional or I do feel like I'm overreacting?
  • What is my current overall stress level (none, low, medium, high, where none is the perfect vacation)?
  • Is my reaction made worse due to other factors (other stress, being tired, etc)?
  • Are there logical steps I can take to remove the stress?
  • Are there logical steps I can take to mitigate the stress?
  • Will taking a day off or a vacation help the situation?

Now imagine showing this list to someone you really trust, would they call you on any of your answers? If a co-worker had written the answers, what other advice would you offer? I'm not advocating showing anyone the list, but it's a useful exercise to help you look at your situation objectively. From there, take the logical steps you've thought of and do something after work that you enjoy, something that will take your mind off of it.

The second pattern is 'cumulative stress'. This builds up when you have multiple things going on at the same time that cause you stress, usually in addition to being tired (or sick). I'll bet you've all seen someone at the office that shows some or all of these symptoms:

  • Complaining a lot, not a lot of fun to be around
  • More time than usual spent not working (web browsing, hall chats, coming in late or leaving early) or working ineffectively (output drops)
  • Making dumb mistakes
  • Slower than usual to respond to email about work
  • Messier than usual work environment
  • Combative with co-workers and/or significant other

Cumulative stress requires a break at a minimum, at least a week and two is better. Sometimes a break is all you need, sometimes you also need to change your response to the things that cause you stress or you'll be back in the same place all too soon. If you see yourself exhibiting these symptoms, find a way to take a break and at the end of the break, evaluate whether you need to spend time on the immediate stress items before you go back.

There are a couple other things you can do to help you monitor your stress level. One is to maintain a short log where you score each work day on a scale of 1 to 5, and include in the log why that day was stressful. I suspect over time you'll see and confirm some interesting patterns. The other is to calculate an ad hoc stress index for yourself (knowing that we geeks love numbers) by keeping a running 15 or 30 day average of your stress level based on your log. If you see the average staying in the 4-5 range you'll know it's time to make changes, whether it be reassessing how you react to some stressful items, taking a break, or both.

Stress is real. Managing stress is not a zen exercise, it's a life skill that most of us aren't as good at as we need to be. I hope that reading this will encourage you to think about your response to stress, and maybe to seek out a good book or lecture from someone more qualified than me to help you improve your stress management skills.

This article was originally found in
http://www.sqlservercentral.com/columnists/awarren/2557.asp

Wednesday, July 25, 2007

Keep a check on your IDENTITY columns in SQL Server

 The IDENTITY columns, or 'auto number' columns as some people call them, are auto incrementing columns provided by SQL Server. There can only be one IDENTITY column per table. You just have to provide a base value, and an increment value, and SQL Server will take care of incrementing this column automatically. Some people like these, and some don't, but the truth is, IDENTITY columns are gaining popularity, and many production systems, including critical ones are using IDENTITY columns these days. So, it is important to keep an eye on these columns, to make sure they are not reaching the limit of their base data type. For example, if you created an IDENTITY column of smallint datatype, its values can go upto 32767. If you try to insert anymore rows, you will get the following error:

Server: Msg 8115, Level 16, State 1, Line 1
Arithmetic overflow error converting IDENTITY to data type smallint.
Arithmetic overflow occurred.

If this table happens to be a part of a critical production system, then you are in trouble. You will have to do something about it to resolve it. If the data from this table can be deleted, then delete the data using TRUNCATE TABLE command. TRUNCATE TABLE resets the IDENTITY column to its base value. The DELETE command doesn't do this. But then, if this table is referenced by a foreign key, then TRUNCATE TABLE is not allowed on this table. Your other option is to run DBCC CHECKIDENT on your table with RESEED option.

An IDENTITY column of tinyint datatype can go upto 255, smallint can go upto 32767, int can go upto 2147483647 and bigint can go upto 9223372036854775807.

You can proactively monitor these IDENTITY columns, to avoid getting into such problems. If you can see in advance, that an IDENTITY column is reaching its limit, then you could do something about it, before it reaches the limit. The other day, one of my friends was trying to automate a process that checks all the IDENTITY columns in a database and reports on how far away those columns are from the limit. He was using a cursor to go through all the tables in the database, and running a "SELECT MAX(IdentityCol) FROM TableName" on all the tables that have an IDENTITY column. It would take ages to run on a database with many big tables. It can be simplified into one simple query using IDENT_CURRENT function. That's what I did, and thought it will be useful for other DBAs as well. So, here I am writing about it.

There are three different versions of this procedure. First one is for SQL Server 2005. The second and third versions work in SQL Server 2000. You will have to create this procedure in the database of your interest. And run it as shown below:

EXEC dbo.CheckIdentities
GO

This procedure below, displays information about all IDENTITY columns in the database, and shows you the percentage of IDENTITY values already used. If you are seeing any IDENTITY columns that have used up 80% or more values, then you need to start thinking about it. You could customise this procedure to automatically email you or log an error if there are any IDENTITY columns that are nearing the limit. You could also schedule this procedure as an SQL Agent job, so that it checks these columns regularly. Any new IDENTITY columns added to the database will automatically get picked up by this query.

A quick note about 64 bit SQL Server. Even though SQL Server 64 bit editions can access a lot more memory inherently, than the 32 bit systems could - the IDENTITY columns are still limited to the limits imposed by the base datatypes. I'm writing this because, someone recently asked me if int data type can store a higher number in 64 bit server, compared to a 32 bit server.

/* The SQL Server 2005 version of the stored procedure. It uses new catalog views */


CREATE PROC dbo.CheckIdentities
AS
BEGIN
SET NOCOUNT ON

SELECT QUOTENAME(SCHEMA_NAME(t.schema_id)) + '.' + QUOTENAME(t.name) AS TableName,
c.name AS ColumnName,
CASE c.system_type_id
WHEN 127 THEN 'bigint'
WHEN 56 THEN 'int'
WHEN 52 THEN 'smallint'
WHEN 48 THEN 'tinyint'
END AS 'DataType',
IDENT_CURRENT(SCHEMA_NAME(t.schema_id) + '.' + t.name) AS CurrentIdentityValue,
CASE c.system_type_id
WHEN 127 THEN (IDENT_CURRENT(SCHEMA_NAME(t.schema_id) + '.' + t.name) * 100.) / 9223372036854775807
WHEN 56 THEN (IDENT_CURRENT(SCHEMA_NAME(t.schema_id) + '.' + t.name) * 100.) / 2147483647
WHEN 52 THEN (IDENT_CURRENT(SCHEMA_NAME(t.schema_id) + '.' + t.name) * 100.) / 32767
WHEN 48 THEN (IDENT_CURRENT(SCHEMA_NAME(t.schema_id) + '.' + t.name) * 100.) / 255
END AS 'PercentageUsed'
FROM sys.columns AS c
INNER JOIN
sys.tables AS t
ON t.[object_id] = c.[object_id]
WHERE c.is_identity = 1
ORDER BY PercentageUsed DESC
END



If you try to create the above stored procedure in SQL Server 2000, you will get the following error:

Server: Msg 195, Level 15, State 10, Procedure a, Line 4 'SCHEMA_NAME' is not a recognized function name. So, here are some SQL Server 2000 compatible versions. /* The SQL Server 2000 version of the stored procedure. Uses system tables. This should work in SQL Server 7.0 too */




CREATE PROC dbo.CheckIdentities
AS
BEGIN
SET NOCOUNT ON

SELECT QUOTENAME(USER_NAME(t.uid))+ '.' + QUOTENAME(t.name) AS TableName,
c.name AS ColumnName,
CASE c.xtype
WHEN 127 THEN 'bigint'
WHEN 56 THEN 'int'
WHEN 52 THEN 'smallint'
WHEN 48 THEN 'tinyint'
END AS 'DataType',
IDENT_CURRENT(USER_NAME(t.uid) + '.' + t.name) AS CurrentIdentityValue,
CASE c.xtype
WHEN 127 THEN (IDENT_CURRENT(USER_NAME(t.uid) + '.' + t.name) * 100.) / 9223372036854775807
WHEN 56 THEN (IDENT_CURRENT(USER_NAME(t.uid) + '.' + t.name) * 100.) / 2147483647
WHEN 52 THEN (IDENT_CURRENT(USER_NAME(t.uid) + '.' + t.name) * 100.) / 32767
WHEN 48 THEN (IDENT_CURRENT(USER_NAME(t.uid) + '.' + t.name) * 100.) / 255
END AS 'PercentageUsed'
FROM syscolumns AS c
INNER JOIN
sysobjects AS t
ON t.id = c.id
WHERE COLUMNPROPERTY(t.id, c.name, 'isIdentity') = 1
AND OBJECTPROPERTY(t.id, 'isTable') = 1
ORDER BY PercentageUsed DESC
END


/* The SQL Server 2000 version of the stored procedure. Uses INFORMATION_SCHEMA views. */


CREATE PROC dbo.CheckIdentities
AS
BEGIN
SET NOCOUNT ON

SELECT QUOTENAME(t.TABLE_SCHEMA) + '.' + QUOTENAME(t.TABLE_NAME) AS TableName,
c.COLUMN_NAME AS ColumnName,
c.DATA_TYPE AS 'DataType',
IDENT_CURRENT(t.TABLE_SCHEMA + '.' + t.TABLE_NAME) AS CurrentIdentityValue,
CASE c.DATA_TYPE
WHEN 'bigint' THEN (IDENT_CURRENT(t.TABLE_SCHEMA + '.' + t.TABLE_NAME) * 100.) / 9223372036854775807
WHEN 'int' THEN (IDENT_CURRENT(t.TABLE_SCHEMA + '.' + t.TABLE_NAME) * 100.) / 2147483647
WHEN 'smallint' THEN (IDENT_CURRENT(t.TABLE_SCHEMA + '.' + t.TABLE_NAME) * 100.) / 32767
WHEN 'tinyint' THEN (IDENT_CURRENT(t.TABLE_SCHEMA + '.' + t.TABLE_NAME) * 100.) / 255
END AS 'PercentageUsed'
FROM INFORMATION_SCHEMA.COLUMNS AS c
INNER JOIN
INFORMATION_SCHEMA.TABLES AS t
ON c.TABLE_SCHEMA = t.TABLE_SCHEMA AND c.TABLE_NAME = t.TABLE_NAME
WHERE COLUMNPROPERTY(OBJECT_ID(t.TABLE_SCHEMA + '.' + t.TABLE_NAME), c.COLUMN_NAME, 'isIdentity') = 1
AND c.DATA_TYPE IN ('bigint', 'int', 'smallint', 'tinyint')
AND t.TABLE_TYPE = 'BASE TABLE'
ORDER BY PercentageUsed DESC
END





You could read the original article from the following link: http://vyaskn.tripod.com/sql_server_check_identity_columns.htm

Friday, June 15, 2007

Solution for "UNICODE ASP files are not supported" error in .Net

Error – ASP.Net
Active Server Pages error 'ASP 0239'
Cannot process file
/GR/submit_page.asp, line 1
UNICODE ASP files are not supported


Solution
With your project open, click on File, Advanced Save Options. Select US-ASCII.
Then click to apply to ALL DOCUMENTS. 
It will give you a warning that some characters may not play, but you can ignore that.
From that point forward, all saves should be in ASCII and your pages will play.

Provided by Ravichander Kannan, GTS, CSC India


Please visit my other blogs too: http://edwardanil.blogspot.com for information and http://netsell.blogspot.com for internet marketing. Thanks !!

Thursday, July 27, 2006

A Fix() Function in T-SQL

Someone today asked me for a SQL Server function that would round a number to the first two significant places. The idea would be that 0.243 would round to 0.24, 0.00592 would round to 0.0059, and 34600 would round to 35000.

Like all good developers, I start with creating some tests. :)

I'm not using a proper testing tool here, this is just for fun - so I'm going to just make a resultset with two columns - the one that I should get, and the one that I expect to get. And I'll throw in a couple of extra numbers, to make sure I cater for the negative cases as well.

select * from
( select 0.243 param, dbo.fix(0.243) result, 0.24 wanted
union all select 0.00592, dbo.fix(0.00592), 0.0059
union all select 34600, dbo.fix(34600), 35000
union all select -3323, dbo.fix(-3323), -3300
union all select -3.59, dbo.fix(-3.59), -3.6
) t
where t.result <> t.wanted

Obviously this won't work yet, I don't have a function called fix (which I'm naming for the comparison with the 'fix' function in other systems). So let's create it:

create function dbo.fix(@num float) returns float as
begin
return (@num)
end

I'm using float because I'm lazy. I could use numeric, but float is quick to type, and does the job for now.

Right. Now I run my test, and all five results come back. Lovely. So now let's fix the function.

So how do we do this... well, the round() function in SQL Server will round a number nicely. It takes a parameter which is the number of decimal places you want. And it takes negative numbers. round(12345,-3) gives 12000. That's just what I'm after. So let's think about it. I want the length of the number. The length of 12345 is obviously 5 - so that works. I can convert the number into a string, count the length and get 5. Then I can get -3 from it by subtracting it from 2, which is the number of significant places I want.

Terrific. That'll work for positive integers. But the length of "1.2345" is 6, which clearly isn't right.

Here's where I feel myself turning into a real geek. I'm going to use the log10() function. log10(12345) is 4.09. Better still, log10(999) is 2.9996 and log10(1000) is 3. That's terrific. I can round that number down, add one, and there's my number length. It even works for fractions. log10(1.2345) is a little over 0, log10(0.9) is just under 0. log10(0.00343) is about -2.5. So if I round all these DOWN (that's the floor() function), and add one, I get what I need the length to be. I can't use the ceiling() function, because that wouldn't work for 1000 - for which I want a length of 4, not 3. I do actually need to round down and then add one, in case rounding down doesn't do anything.

So now I have my 'length', and if I subtract that from 2, then hopefully I get the number that I can use for the round function.

alter function dbo.fix(@num float) returns float as
begin
declare @res float
select @res = round(@num,2-(1+floor(log10(@num))))
return (@res)
end

Well this seems to do it. Of course I could change the 2 to a 1, and stop adding one to my floor. I run my test query, and no rows are returned. Great. All done.

Except that it isn't. High-school maths reminds me that you can't take the log of a negative number. So what's going on with my tests? I check the Messages (rather than the results grid), and I see a domain error has occurred. It'd be nice if this would kick a proper error, one that would display red text and stop my query from running at all, but such is life.

Either way, we know it's a problem now, so we can fix it.

I can't take the log of a negative number, so let's check to see if the number if negative, and if it is, we can use the log of the negative number instead. I mean, I still want to round 3.6 with a value of 1, and -34334 with -3. So I'll put a case statement into my function:

alter function dbo.fix(@num float) returns float as
begin
declare @res float
select @res = case
when @num > 0 then round(@num,1-floor(log10(@num)))
else round(@num,1-floor(log10(-@num)))
end
return (@res)
end

Now my test works without an error message. "(0 row(s) affected)" is what I want to see, and there it is. I'm happy.

A minor change is to let it take another function to show many significant digits are required. Simple change:

alter function dbo.fix(@num float, @digits int) returns float as
begin
declare @res float
select @res = case
when @num > 0 then round(@num,@digits-1-floor(log10(@num)))
else round(@num,@digits-1-floor(log10(-@num)))
end
return (@res)
end

And the guy who asked me for this? Well, he's gobsmacked that there really is a use for logarithms in the real world.

Original Source: http://www.sqlservercentral.com/articles/Advanced+Querying/afixfunctionintsql/2487/