Temporary Tables vs. Table Variables in SQL Server

May 9th, 2009 by nilesh.shamnani § 6

When writing T-SQL code, you often need a table in which to store data temporarily when it comes time to execute that code. You have four table options: normal tables, local temporary tables, global temporary tables and table variables. I’ll discuss the differences between using temporary tables in SQL Server versus table variables. Each of the four table options has its own purpose and use, and each has its benefits and issues:

  • Normal tables are exactly that, physical tables defined in your database.
  • Local temporary tables are temporary tables that are available only to the session that created them. These tables are automatically destroyed at the termination of the procedure or session that created them.
  • Global temporary tables are temporary tables that are available to all sessions and all users. They are dropped automatically when the last session using the temporary table has completed. Both local temporary tables and global temporary tables are physical tables created within the tempdb database.
  • Table variables are stored within memory but are laid out like a table. Table variables are partially stored on disk and partially stored in memory. It’s a common misconception that table variables are stored only in memory. Because they are partially stored in memory, the access time for a table variable can be faster than the time it takes to access a temporary table.

Creating indexes on SQL Server tables

Because both local and global temporary tables are physical tables within the tempdb database, indexes can be created on these tables to increase performance as needed. As with any index creation, this process can take time on larger tables. Because temp tables are physical tables, you can also create a primary key on them via the CREATE TABLE command or via the ALTER TABLE command. You can use the ALTER TABLE command to add any defaults, new columns, or constraints that you need to within your code.

Unlike local and global temporary tables, table variables cannot have indexes created on them. The exception is that table variables can a primary key defined upon creation using the DECLARE @variable TABLE command. This will then create a clustered or non-clustered index on the table variable. The CREATE INDEX command does not recognize table variables. Therefore, the only index available to you is the index that accompanies the primary key and is created upon table variable declaration.

How do the internal workings of SQL Server perform differently between table variables and temporary tables?

The differences between accessing tables and variables cause the internal processes within SQL Server to treat the objects quite differently. Temporary tables are actually physical tables, so the SQL Optimizer and locking engine handle the tables just as they would any other database tables. Because reads to a temporary table are made (including local temporary tables), a read lock is placed on the table.

This locking process takes time and CPU resources. When reading from a table variable – because the table variable is stored partially within memory and cannot be accessed by any other user or process on the system – SQL Server knows locking is not required. In a very busy database, this lack of locking can improve system performance because locks do not have to be taken, escalated and checked for each data access operation.

Limits of temporary tables and table variables

Temporary tables and table variables both have their strengths, but they both have weaknesses too. On a heavy load system that has lots of usage of temporary tables, the disk array servicing the tempdb database will experience a higher than expected load. This happens because all reads and writes to the temporary tables are done within the tempdb database. Table variables will perform poorly with large record sets, especially when doing joins because there can be no indexes other than a primary key. Beware, though, when many users start using table variables — large amounts of RAM are used because all temporary tables are stored and processed directly in memory. Table variables should hold no more than 2 Megs to 3 Megs of data each (depending on user load and system memory).

Both temporary tables and table variables can be extremely useful tools in developers’ and administrators’ arsenals; however, care must be taken as to when to use each solution. There is no end-all solution, and you must choose the correct solution for the correct situation.

Local Temporary tables:

They are created using same syntax as CREATE TABLE except table name is preceded by ‘#’ sign. When table is preceded by single ‘#’ sign, it is defined as local temporary table and its scope is limited to session in which it is created.

Open one session in Query Analyzer or SSMS (Management Studio) and create a temporary table as shown below.

CREATE TABLE #TEMP
(
COL1 INT,
COL2 VARCHAR(30),
COL3 DATETIME DEFAULT GETDATE()
)

GO

Upon successful execution of above command, MS SQL Server creates table in tempdb database. One cannot create another temporary table with the same name in the same session. It will give an error but table with the same name can be created from another session. To do this, open another session from SSMS or query analyzer and issue same command again. It will successfully create new temporary table for that session.

In order to identify which table is created by which user (in case of same temporary table name), SQL Server suffixes it with the number. This is very common scenario when temporary table is defined in the stored procedure and procedure is getting executed by different users simultaneously. Since we have created temporary table with the same name from two different sessions, we should see two entries in tempdb database. From another session or any of the current session, issue following command. Output is displayed after select statement.

USE TEMPDB
GO
SELECT Table_Catalog, Table_Name FROM information_schema.tables
WHERE table_name like ‘%TEMP%’
GO

Table_Catalog Table_Name
————- ———-
tempdb #TEMP________0000000001F7
tempdb #TEMP________0000000001F9

Now create some data from the session in which temporary table (#temp) is created.

INSERT INTO #TEMP(COL1, COL2) VALUES(1,’Decipher’);
INSERT INTO #TEMP(COL1, COL2) VALUES(2,’Information’);
INSERT INTO #TEMP(COL1, COL2) VALUES(3,’systems’);

Selecting data from temporary table will give following results.

COL1 COL2 COL3
———– —————————— ———————–
1 Decipher 2007-03-27 19:39:56.727
2 Information 2007-03-27 19:39:56.727
3 systems 2007-03-27 19:39:56.727

This data is not visible from another session since we are using local temporary table. We can verify it by connecting to another session and querying the #temp table. Local temporary tables are dropped when session which created the table is ended, if one has not dropped it explicitly.

Also, please do note that if you are creating temp tables in a stored procedure, the scope for the existence of those temporary tables is only the procedure execution. The temp tables automatically get dropped once the procedure execution is over (they can be explicitly dropped as well). Once the procedure execution is over, those temp tables will not be accessible from within that session. Example:

create proc test
as
begin
set nocount on
create table #temp (col1 int)
insert into #temp values (1)
end
go

exec test
select * from #temp

Msg 208, Level 16, State 0, Line 2
Invalid object name ‘#temp’.

Global Temporary tables:

Syntax difference between global and local temporary table is of an extra ‘#’ sign. Global temporary tables are preceded with two ‘#’ (##) sign. Following is the definition. In contrast of local temporary tables, global temporary tables are visible across entire instance.

CREATE TABLE ##TEMP_GLOBAL
(
COL1 INT,
COL2 VARCHAR(30),
COL3 DATETIME DEFAULT GETDATE()
)
GO

Execute above statement to create global temporary table. You can verify it by checking the tempdb database. As global temporary tables are available across the instance, SQL Server doesn’t suffix it with the number. Following is the output of query ran against tempdb.

USE TEMPDB
GO
SELECT Table_Catalog, Table_Name FROM information_schema.tables
WHERE table_name like ‘##TEMP%’
GO

Table_Catalog Table_Name
————- ———-
tempdb ##TEMP_GLOBAL

There will be only single instance of global temporary table. Attempt of creating global temporary table with the same name from any other session will result into an error.

Create some data in one of the session where temporary table (##temp_global) is created.

INSERT INTO ##TEMP_GLOBAL(COL1, COL2) VALUES(1,’Decipher’);
INSERT INTO ##TEMP_GLOBAL(COL1, COL2) VALUES(2,’Information’);
INSERT INTO ##TEMP_GLOBAL(COL1, COL2) VALUES(3,’systems’);

Connect to other existing session or open new session. Execute following statement and you will notice that global temporary table is available along with the data from other session as well.

COL1 COL2 COL3
———– —————————— ———————–
1 Decipher 2007-03-28 09:52:34.310
2 Information 2007-03-28 09:52:34.310
3 systems 2007-03-28 09:52:34.310

Global temporary tables are dropped when last session accessing the tables is closed. It is always good practice to drop the temporary tables in the same scope, once we are done with it. This will help us in avoiding creation error when same connection from the connection pool is used by different processes which access temporary tables.

Global temporary tables can be used in data warehousing application where one session performs the ETL and populate the global temporary tables and other sessions read from the table, specific data and process it.

Features of Temp Tables

We’ll list out features that differentiate a Temp Table between either a Permanent Table or a Table variable. These pointers will be helpful to keep in mind when you consider Table Variables in our next post.

Scope: Within a connection, a temporary table object is visible to the creating level and inner levels (nested). For example, if you create a stored procedure and declare a temporary table object within it, you can call another stored procedure from that stored procedure (a nested stored procedure) and perform operations like inserting, updating and deleting that temporary table object. Once the main creating level terminates, the temp table is automatically destroyed. But don’t be too complacent – you’ll have to wait for the system to perform a clean up and therefore, it is highly recommended that you manually drop your temporary table.

Locking: The prospect of table locking is reduced when it comes to local temporary tables since this table is being used by only one user. One aspect where you might want to keep this in mind is that if you cancel a transaction which contains the creation of a temp table object and then cancel that query, an exclusive and update lock can appear on the tempdb. This lock will persist till the complete transaction has closed with a COMMIT or a ROLLBACK

Logging: There is less logging involved with temporary tables compared to permanent tables.

Transaction: When using a temporary table, a temporary table is an integral part of an outer transaction and therefore, ROLLBACKs must be supported by Logging

Indexing: We can create indexes on temporary tables explicitly on them. Hence, there is scope for performance enhancement when you talk about temp tables.

Constraints: All constraints are available for exploiting on a temp table EXCEPT when it comes to referring a Foreign Key Constraints

Statistics: SQL Server can create Statistics for temp tables just like we do for permanent tables and therefore, the query optimizer has the option of choosing different plans. Hence, with this in mind, be aware of the scope of Stored Procedure Recompiles.

Recompiles: There is scope for a large number of Stored Procedure Recompiles especially when you have DDL statements mixed anywhere within your Stored Procedure.

Temp Table Size: Can hold any volume of data. This will be a strong part of the deciding factor when you want to choose between a temporary table and a table variable.

Features of Table Variables

Now that you’ve got a hang around working with a Table Variable, let me mention the main pointers that we need to keep in mind while working with. This will set the stage for differentiating between a Temp Table and Table Variable which I’ll illustrate in my next post.

Transactions: Table Variables are not bound to any transaction as they are just like any other variable

Minimum Constraints: A Table Variable permits us to use only the PRIMARY KEY, UNIQUE KEY and NULL constraint only. What this implies behind the scenes is that we can have unique indexes. The only possibility of creating a non-unique index is if we add attributes and make that blend unique and have a PRIMARY KEY or a UNIQUE KEY on the combination we just made.

No SELECT INTO: We cannot use a SELECT INTO with Table Variables in SQL Server 2000 though the feature is available with Table Variables in SQL Server 2005. Likewise, we can also have INSERT INTO working with Table Variables against a SELECT but not against an EXEC Stored Procedure.

No ALTER TABLE Variable: We cannot ALTER a Table once it has been declared. This may look a little rigid but remember that recompilations can come out like wild fire when there are DDL (Data Definition Language .i.e Schema) changes and therefore, this helps to avoid recompilations.

Scope: Just like any other variable, a Table Variable’s scope exists only within the context of the current level. Therefore, unlike Temp Tables, it is not accessible to sub levels (of Stored Procedures)

Table Variables And The TempDb: Okay, now I’ll touch upon one of the most common myths that exist among developers: that Table Variables have nothing to do with TempDb and therefore, they have no physical representation in the TempDb and therefore, they reside in ONLY memory and therefore they’re the best option for efficient processing.

Not entirely true. Table Variables do indeed have a physical representation within the TempDb and this can proved with a simple query in your database against the TempDb:

No Statistics: When it comes to Table Variables, the SQL Server optimizer does not create distribution statistics. Therefore, you run the risk of referring not-so-good query plans when the SQL Server optimizer selects after checking up with histograms. And if you consider this aspect with Tables Variables that contain huge amounts of data, we fall into serious I/O thrashing. Hence, as stated in the closing section of the last point, we have to have a thorough understanding of our scenario to choose a temporary object for the context.

A possible replacement for temp tables is a table variable.

In summary, following are the key points when temporary tables are involved.

  • Temporary tables can be defined as local or global temporary tables.
  • Local temporary tables are available to session in which they are created. If another  session creates the table with the same name, it will be different copy of the table in tempdb database.
  • Global temporary tables are available across the instance. Any user from any session can access it.
  • It is best practice to drop the temporary table when related work is finished rather than relying on connection to end for the cleanup.
  • Table variables can be used instead of temporary tables for performance reasons and when dealing with smaller sub-sets.
  • When used in the procedure,function or trigger, its scope ends once execution is completed.

Limitations of Temporary Tables

Temporary tables are created in the tempdb database and create additional overhead for SQL Server, reducing overall performances. SQL Server has numerous problems with operations against temporary tables.

Using Temporary Tables Effectively

If you do not have any option other than to use temporary tables, use them affectively. There are few steps to be taken.

  • Only include the necessary columns and rows rather than using all the columns and all the data which will not make sense of using temporary tables. Always filter your data into the temporary tables.
  • When creating temporary tables, do not use SELECT INTO statements, Instead of SELECT INTO statements, create the table using DDL statement and use INSERT INTO to populate the temporary table.
  • Use indexes on temporary tables. Earlier days, I always forget to use a index on temporary. Specially, for large temporary tables consider using clustered and non-clustered indexes on temporary tables.
  • After you finish the using your temporary table, delete them. This will free the tempdb resources. Yes, I agree that temporary tables are deleted when connection is ended. but do not wait until such time.
  • When creating a temporary table do not create them with a transaction. If you create it with a transaction, it will lock some system tables (syscolumns, sysindexes, syscomments). This will prevent others from executing the same query.

Conclusion

Generally, temporary tables should be avoided as much as possible. If you need to use them follow the steps above so that you have the minimum impact on server performance

If you have to use a temp table, do not create it from within a transaction. If you do, then it will lock some system tables (syscolumns, sysindexes, and syscomments) and prevent others from executing the same query, greatly hurting concurrency and performance. In effect, this turns your application into a single-user application.

To avoid this problem, create the temporary table before the transaction. This way, the system tables are not locked and multiple users will have the ability to run this same query at the same time, helping concurrency and performance.

Convert HTML To Plain Text By RegularExpressions

May 9th, 2009 by dhruval.shah § 0

This is a procedure for stripping out HTML tags while preserving the most basic formatting.  

In other words, it converts HTML to plain text.

// Return Plain Text
private string ConvertHtmlToPlainText(string htmlText)
{
return System.Text.RegularExpressions.Regex.Replace(htmlText, “<[^>]*>”, string.Empty);
}

Enjoy!

SQLAuthority News – Scrum: Agile Software Development for Project Management

May 7th, 2009 by pinaldave § 1

This is something I have learned while working for so many years as Project Manager. It is not as important to know how things are done but it is important to know how to get things done. Scrum is an Agile Software Development system which helps developers to get project done in reasonable time and with superior quality.

The most important elements of Scrum are. These are presented below.

Scrum is organized around the following roles:

  • Product Owner – Determines what functionality is needed
  • ScrumMaster – Leads the Scrum and is primarily responsible for making sure the Scrum process is followed and removing impediments that keep the Team from working
  • The Team – Those who do the actual work that translates what the Product Owner has requested into usable functionality

The following is a synopsis of the Scrum process:

  • The Product Owner creates the Product Backlog (List of Desired Functionality in the System)
  • A meeting is held with the Product Owner, the ScrumMaster and the Team
  • The Team commits to getting x number of items from the Product Backlog done in 30 days. This 30 day block is known as the Sprint
  • The Team makes a Sprint Backlog (List of items that must be done to turn the Product Backlog items into shippable items during the Sprint)
  • The ScrumMaster meets with the Team daily and asks each member three questions:
    • What have you completed for the Sprint in the last day?
    • What will you complete for the Sprint tomorrow?
    • Is anything impeding you from getting your work done?
  • The Daily Scrum causes the Team to reveal exactly where it is, or where it isn’t
  • The ScrumMaster keeps distractions away from the Team
  • The Team self-organizes and keeps the Sprint Backlog up-to-date
  • An item on the Sprint Backlog is done when code is well-written, well-structured and thoroughly tested
  • At the end of the Sprint, a Sprint Review meeting is held
  • Items not completed during a Sprint are allocated to a future Sprint

Other important notes to keep in mind when utilizing the Scrum process:

  • Scrum makes a project’s progress and problems constantly visible
  • Every Sprint produces an increment of potentially shippable functionality
  • Scrum must be put into place before it can be fully understood
  • Scrum focuses on what can be done
    • It instills the “art of the possible” and allows work to go forward before things are “perfect”
    • You will never achieve perfection, no matter how much planning you do
    • Sprints are time-boxed to keep the team from searching too much for perfection
    • Focus efforts on a small set of pressing problems
    • Define work that will allow concrete results
    • Planning doesn’t have to be extensive for a Scrum project to get going
    • The minimum is a vision and a Product Backlog
  • Scrum is anti-sequential
    • Get going on what can be done
    • Help each other out
    • Collaborate
    • Sequential tasks divide a team
  • In Scrum, an estimate is not a contract
    • Scrum expects exceptions to the plan and doesn’t fear them
    • Adaptation is a normal part of the process

Reference : Pinal Dave (http://blog.SQLAuthority.com), Comments from Scrum Team Members, Many Online Resources

SQL Injection and Prevention of SQL Injection

May 6th, 2009 by dhaval.shah § 0

What is SQL Injection?

SQL injection is a technique that exploits a security vulnerability occurring in the database layer of an application. This vulnerability is present when user input is manipulated for string literal escape characters embedded in SQL statements or user input is not sufficiently filtered and thereby unexpectedly executed.

How SQL Injection looks like?

Basic SQL Injections

If anybody want to pull up the records of particular user name from the user information table and if “username” variable is set as

X‘ OR ‘Y‘ = ‘Y

By inputting the above code as user name , Let see how’s it work at back end?

SELECT * FROM UserInformation WHERE UserName = X’ OR ‘Y’ = ‘Y’

If we use this type of code were in an authentication procedure then this example could be used to force the selection of a valid “username” because the evaluation of ‘Y’='Y’ is always true and you will be logged in as the user on top of the SQL table.

Same way if the “username” variable is set as

X‘ OR 1 = 1 –-

If we use double dashes (–) than at the back end these dashes at the end tell the SQL server to ignore the rest of the query.

SELECT * FROM UserInformation WHERE UserName = X’ OR 1 = 1 –-

Same way more SQL Injection syntaxes are:

‘) OR (‘1’ = ‘1

‘ OR ‘1’ = ‘1

‘ OR 1 = 1

“ OR “1”= “1

“ OR 1 = 1 –-

OR 1 = 1 –-

How can we get free from SQL Injection?

  • Validate all input before using it.We can validate the input by this way.Reject the input that contains the following characters:

1. Single Quote(‘)

2.  Dash ( – )

3.  /* and */

4. Semicolon ( ; )

  • User parameterized input with stored procedures: Stored procedures may be susceptible to SQL injection if they use unfiltered input. So all the input provided to the stored Procedures is provided in the form of parameters
  • Filtering input: Replace a Single Quote (‘) with two Single Quotes (‘’) to filter the input.
  • Limit the database permission: Use a limited access account to connect to the database
  • Don’t store secrets in plain text: Encrypt or hash passwords and other sensitive data; you should also encrypt connection strings
  • Exceptions should divulge minimal information: Don’t expose too much information in error messages; display minimal information in the event of error handling.

Reference :

http://en.wikipedia.org/wiki/SQL_injection

http://www.secureworks.com/research/articles/sql-injection-attacks

 

How to integrate Uber uploader in CakePHP

May 2nd, 2009 by nayan.lodha § 2

Uber-Uploader

Uber-Uploader is a group of programs written in Perl, PHP and Javascript. It is intended to present a graphical representation of the status of a web based file upload in the form of a progress bar.

External Links

CakePHP

CakePHP is a free, open-source, rapid development framework for PHP. It’s a foundational structure for programmers to create web applications. Our primary goal is to enable you to work in a structured and rapid manner–without loss of flexibility.

CakePHP takes the monotony out of web development. We provide you with all the tools you need to get started coding what you really need to get done: the logic specific to your application. Instead of reinventing the wheel every time you sit down to a new project, check out a copy of CakePHP and get started with the real guts of your application.

Why We Need To Integrate CakePHP With Uber-Uploader

As mention above  Uber-Uploader is a group of programs written in Perl, PHP and Javascript.It is used to upload large volume video files.It also provide a very good GUI as progress bar and show some  informaton like Elapsed Time ,Est Time Left ,Percent Complete etc that helps user to keep patience while upload a large volum files.

Here is the some steps How to integrate uber uploader in cakePHP

1.Create a folder in Webroot/files and put all files in that folder
eg. i created ‘uploder’ in webroot/files than i created ‘html’ folder in ‘uploder’ folder

2.Set the $TEMP_DIR value in ‘ubr_upload.pl’ AND ‘ubr_ini.php’.
eg. $TEMP_DIR = ‘/xyz.com/html/tmp/ubr_temp/’;
eg. $TEMP_DIR = ‘/var/tmp/ubr_temp/’;
eg. $TEMP_DIR = ‘/usr/home/roger/ubr_temp/’;

3.Set the $_CONFIG['upload_dir'] value in ‘ubr_default_config.php’. It should be physical path
eg. $_CONFIG['upload_dir'] = ‘/XYZ.com/app/webroot/files/uploader/html/tmp/ubr_uploads’;
eg. $_CONFIG['upload_dir'] = ‘/var/www/html/ubr_uploads/’;
eg. $_CONFIG['upload_dir'] = ‘/usr/local/www/htdocs/ubr_uploads/’;
eg. $_CONFIG['upload_dir'] = $ENV{‘DOCUMENT_ROOT’} . ‘/ubr_uploads/’;

4.Set the correct path values for the scripts in ‘ubr_ini.php’.
eg. PATH_TO_UPLOAD_SCRIPT       = ‘../app/webroot/files/uploader/html/cgi-bin/ubr_upload.pl’;      // Path info
PATH_TO_LINK_SCRIPT         = ‘../app/webroot/files/uploader/html/ubr_link_upload.php’;        // Path info
PATH_TO_SET_PROGRESS_SCRIPT = ‘../app/webroot/files/uploader/html/ubr_set_progress.php’;       // Path info
PATH_TO_GET_PROGRESS_SCRIPT = ‘../app/webroot/files/uploader/html/ubr_get_progress.php’;       // Path info
PATH_TO_JS_SCRIPT           = ‘../app/webroot/files/uploader/html/ubr_file_upload.js’;         // Path info
PATH_TO_JQUERY              = ‘../app/webroot/files/uploader/html/jquery-1.3.1.min.js’;        // Path Info
PATH_TO_CSS_FILE            = ‘../app/webroot/files/uploader/html/ubr.css’;                    // Path info
DEFAULT_CONFIG              = ‘/XYZ.com/app/webroot/files/uploader/html/ubr_default_config.php’;     // Path info

5.Make ubr_pload.pl executable with the command chmod 755 ubr_pload.pl

6.Set the correct path for $_CONFIG['redirect_url']  in ‘ubr_default_config.php’

7.Set the correct path for $_CONFIG['path_to_upload'] and $_CONFIG['upload_dir'] in ‘ubr_default_config.php’.It is the Directory where the video get uplaod
eg. /home/xyz.com/app/webroot/files/uploader/html/tmp/ubr_uploads/

8.Make sure that both path ($_CONFIG['path_to_upload'] and $_CONFIG['upload_dir']) should be same.

9 Make sure that path for $TEMP_DIR in ubr_upload.pl should be same to $TEMP_DIR value in ‘ubr_ini.php

10.Now Create a action in controller and include the following code
eg  action “uploadvideo” in videos_controller

$this->set(“DEBUG_AJAX”,$DEBUG_AJAX);
$this->set(“PATH_TO_UPLOAD_SCRIPT”,$PATH_TO_UPLOAD_SCRIPT);

$this->set(“PATH_TO_JQUERY”,$PATH_TO_JQUERY);
$this->set(“PATH_TO_GET_PROGRESS_SCRIPT”,$PATH_TO_GET_PROGRESS_SCRIPT);
$this->set(“PATH_TO_SET_PROGRESS_SCRIPT”,$PATH_TO_SET_PROGRESS_SCRIPT);
$this->set(“PATH_TO_CSS_FILE”,$PATH_TO_CSS_FILE);
$this->set(“DEFAULT_CONFIG”,$DEFAULT_CONFIG);
$this->set(“MULTI_CONFIGS_ENABLED”,$MULTI_CONFIGS_ENABLED);
$this->set(“PATH_TO_LINK_SCRIPT”,$PATH_TO_LINK_SCRIPT);
$this->set(“PATH_TO_JS_SCRIPT”,$PATH_TO_JS_SCRIPT);
$this->set(“_CONFIG”,$_CONFIG);

$this->set(“CGI_UPLOAD_HOOK”,$CGI_UPLOAD_HOOK);
$this->set(“GET_PROGRESS_SPEED”,$GET_PROGRESS_SPEED);

$this->set(“DELETE_LINK_FILE”,$DELETE_LINK_FILE);
if($PHP_ERROR_REPORTING){ error_reporting(E_ALL); }

header(‘Content-type: text/html; charset=UTF-8′);
header(‘Expires: Mon, 26 Jul 1997 05:00:00 GMT’);
header(‘Last-Modified: ‘ . date(‘r’));
header(‘Cache-Control: no-store, no-cache, must-revalidate’);
header(‘Cache-Control: post-check=0, pre-check=0′, FALSE);
header(‘Pragma: no-cache’);

//Set config file
if($MULTI_CONFIGS_ENABLED){
// Put your multi config file code here
$config_file = ‘ubr_default_config.php’;
}
else{ $config_file = $DEFAULT_CONFIG; }

// Load config file
require $config_file;
//***************************************************************************************************************
// The following possible query string formats are assumed
//
// 1. No query string
// 2. ?about=1
//***************************************************************************************************************
if($DEBUG_PHP){ phpinfo(); exit(); }
elseif($DEBUG_CONFIG){ debug1($_CONFIG['config_file_name'], $_CONFIG); exit(); }
elseif(isset($_GET['about']) && $_GET['about'] == 1){
kak(“<u><b>UBER UPLOADER FILE UPLOAD</b></u><br>UBER UPLOADER VERSION =  <b>” . $UBER_VERSION . “</b><br>UBR_FILE_UPLOAD = <b>” . $THIS_VERSION . “</b><br>\n”, 1, __LINE__);
}

11. Now put the following code in CTP file(“uploadvideo.ctp” )

<style>
.debug {font:16px Arial; background-color:#FFFFFF; border:1px solid #898989; width:700px; height:100px; overflow:auto;}
.alert {font:18px Arial;}
.data {background-color:#b3b3b3; border:1px solid #898989; width:350px;}
.data tr td {background-color:#dddddd; font:13px Arial; width:35%;}
.bar1 {background-color:#b3b3b3; position:relative; text-align:left; height:20px; width:<?php print $_CONFIG['progress_bar_width']; ?>px; border:1px solid #505050;}
.bar2 {background-color:#000099; position:relative; text-align:left; height:20px; width:0%;}
</style>
<script language=”JavaScript” type=”text/JavaScript” src=”../app/webroot/files/uploader/html/jquery-1.3.1.min.js”></script>
<script language=”javascript” type=”text/javascript” src=”../app/webroot/files/uploader/html/ubr_file_upload.js”></script>
<script language=”javascript” type=”text/javascript”>
var upload_range = 1;
var path_to_link_script = “<?php print $PATH_TO_LINK_SCRIPT; ?>”;
var path_to_set_progress_script = “<?php print $PATH_TO_SET_PROGRESS_SCRIPT; ?>”;
var path_to_get_progress_script = “<?php print $PATH_TO_GET_PROGRESS_SCRIPT; ?>”;
var path_to_upload_script = “<?php print $PATH_TO_UPLOAD_SCRIPT; ?>”;
var multi_configs_enabled = <?php print $MULTI_CONFIGS_ENABLED; ?>;
var check_allow_extensions_on_client = <?php print $_CONFIG['check_allow_extensions_on_client']; ?>;
var check_disallow_extensions_on_client = <?php print $_CONFIG['check_disallow_extensions_on_client']; ?>;
<?php if($_CONFIG['check_allow_extensions_on_client']){ print “var allow_extensions = /” . $_CONFIG['allow_extensions'] . “$/i;\n”; } ?>
<?php if($_CONFIG['check_disallow_extensions_on_client']){ print “var disallow_extensions = /” . $_CONFIG['disallow_extensions'] . “$/i;\n”; } ?>
var check_file_name_format = <?php print $_CONFIG['check_file_name_format']; ?>;
<?php if($_CONFIG['check_file_name_format']){ print “var check_file_name_regex = /” . $_CONFIG['check_file_name_regex'] . “/;\n”; } ?>
<?php if($_CONFIG['check_file_name_format']){ print “var check_file_name_error_message = ‘” . $_CONFIG['check_file_name_error_message'] . “‘;\n”; } ?>
<?php if($_CONFIG['check_file_name_format']){ print “var max_file_name_chars = ” . $_CONFIG['max_file_name_chars'] . “;\n”; } ?>
<?php if($_CONFIG['check_file_name_format']){ print “var min_file_name_chars = ” . $_CONFIG['min_file_name_chars'] . “;\n”; } ?>
var check_null_file_count = <?php print $_CONFIG['check_null_file_count']; ?>;
var check_duplicate_file_count = <?php print $_CONFIG['check_duplicate_file_count']; ?>;
var max_upload_slots = <?php print $_CONFIG['max_upload_slots']; ?>;
var cedric_progress_bar = <?php print $_CONFIG['cedric_progress_bar']; ?>;
var cedric_hold_to_sync = <?php print $_CONFIG['cedric_hold_to_sync']; ?>;
var bucket_progress_bar = <?php print $_CONFIG['bucket_progress_bar']; ?>;
var progress_bar_width = <?php print $_CONFIG['progress_bar_width']; ?>;
var show_percent_complete = <?php print $_CONFIG['show_percent_complete']; ?>;
var show_files_uploaded = <?php print $_CONFIG['show_files_uploaded']; ?>;
var show_current_position = <?php print $_CONFIG['show_current_position']; ?>;
var show_current_file = <?php if($CGI_UPLOAD_HOOK && $_CONFIG['show_current_file']){ print “1″; }else{ print “0″; } ?>;
var show_elapsed_time = <?php print $_CONFIG['show_elapsed_time']; ?>;
var show_est_time_left = <?php print $_CONFIG['show_est_time_left']; ?>;
var show_est_speed = <?php print $_CONFIG['show_est_speed']; ?>;
var JQ = jQuery.noConflict();

JQ(document).ready(function(){
iniFilePage();
JQ(“#upfile_0″).bind(“keypress”, function(e){ if(e == 13){ return false; } });
//JQ(“#upfile_0″).bind(“change”, function(e){ addUploadSlot(1); });
JQ(“#upload_button”).bind(“click”, function(e){ //alert(valid.validate());
if(valid.validate())
linkUpload();
});
JQ(“#reset_button”).bind(“click”, function(e){ resetForm(); });
});
</script>

<script type=”text/javascript” src=”http://www.xyz.com/app/webroot/files/uploader/html/ubr_file_upload.js” ></script>
<link href=”http://www.xyz.com/app/webroot/files/uploader/html/ubr.css” type=”text/css” rel=”stylesheet” />

<!– Start Progress Bar –>
<div align=”center” id=”progress_bar” style=”display:none;”>
<div id=”upload_status_wrap” class=”ubrBar1″  style=”width:400px”>
<div id=”upload_status” class=”ubrBar2″></div>
</div>
<?php if($_CONFIG['show_percent_complete'] || $_CONFIG['show_files_uploaded'] || $_CONFIG['show_current_position'] || $_CONFIG['show_elapsed_time'] || $_CONFIG['show_est_time_left'] || $_CONFIG['show_est_speed']){ ?>
<br>
<table class=”ubrUploadData”>
<?php if($_CONFIG['show_percent_complete']){ ?>
<tr>
<td class=’ubrUploadDataLabel’>Percent Complete:</td>
<td class=’ubrUploadDataInfo’><span id=”percent_complete”>0%</span></td>
</tr>
<?php } ?>
<?php if($_CONFIG['show_files_uploaded']){ ?>
<tr>
<td class=’ubrUploadDataLabel’>Files Uploaded:</td>
<td class=’ubrUploadDataInfo’><span id=”files_uploaded”>0</span> of <span id=”total_uploads”></span></td>
</tr>
<?php } ?>
<?php if($_CONFIG['show_current_position']){ ?>
<tr>
<td class=’ubrUploadDataLabel’>Current Position:</td>
<td class=’ubrUploadDataInfo’><span id=”current_position”>0</span> / <span id=”total_kbytes”></span> KBytes</td>
</tr>
<?php } ?>
<?php if($CGI_UPLOAD_HOOK && $_CONFIG['show_current_file']){ ?>
<tr>
<td class=’ubrUploadDataLabel’>Current File Uploading:</td>
<td class=’ubrUploadDataInfo’><span id=”current_file”></span></td>
</tr>
<?php } ?>
<?php if($_CONFIG['show_elapsed_time']){ ?>
<tr>
<td class=’ubrUploadDataLabel’>Elapsed Time:</td>
<td class=’ubrUploadDataInfo’><span id=”elapsed_time”>0</span></td>
</tr>
<?php } ?>
<?php if($_CONFIG['show_est_time_left']){ ?>
<tr>
<td class=’ubrUploadDataLabel’>Est Time Left:</td>
<td class=’ubrUploadDataInfo’><span id=”est_time_left”>0</span></td>
</tr>
<?php } ?>
<?php if($_CONFIG['show_est_speed']){ ?>
<tr>
<td class=’ubrUploadDataLabel’>Est Speed:</td>
<td class=’ubrUploadDataInfo’><span id=”est_speed”>0</span> KB/s.</td>
</tr>
<?php } ?>
</table>
<?php } ?>
</div>
<!– End Progress Bar –>

<!– Start Upload Form –>
<form name=”form_upload” id=”form_upload” <?php if($_CONFIG['embedded_upload_results'] || $_CONFIG['opera_browser'] || $_CONFIG['safari_browser']){ print “target=\”upload_iframe\”"; } ?> method=”post” enctype=”multipart/form-data”  action=”#” style=”margin: 0px; padding: 0px;”>
<noscript><font color=’red’>Warning: </font>Javascript must be enabled to use this uploader.<br><br></noscript>
<!– Include extra values you want passed to the upload script here. –>
<!– eg. <input type=”text” name=”employee_num” value=”5″> –>
<!– Access the value in the CGI with $query->param(‘employee_num’); –>
<!– Access the value in the PHP finished page with $_POST_DATA['employee_num']; –>
<!– DO NOT USE “upfile_” for any of your values. –>
<div id=”upload_slots”><input type=”file” name=”upfile_0″ size=”90″ <?php if($_CONFIG['multi_upload_slots']){ ?>onChange=”addUploadSlot(1)”<?php } ?>  onkeypress=”return handleKey(event)” value=”"></div>
<br>
<input type=”button” id=”reset_button” name=”reset_button” value=”Reset” onClick=”resetForm();”>&nbsp;&nbsp;&nbsp;<input type=”button” id=”upload_button” name=”upload_button” value=”Upload” onClick=”linkUpload();”>
</form>
<!– End Upload Form –>
</div>
<div id=’ajax_div’><!– Used to store AJAX –></div>

12 Now you can run the code www.xyz.com/videos/uploadvideo

I hope this helps people looking for solution integrating Uber Uploader in Cake PHP. Leave comment in case of any issues.

SQL SERVER – Example of DDL, DML, DCL and TCL Commands

May 2nd, 2009 by pinaldave § 0

DML

DML is abbreviation of Data Manipulation Language. It is used to retrieve, store, modify, delete, insert and update data in database.

SELECT – Retrieves data from a table
INSERT -  Inserts data into a table
UPDATE – Updates existing data into a table
DELETE – Deletes all records from a table

DDL

DDL is abbreviation of Data Definition Language. It is used to create and modify the structure of database objects in database.

CREATE – Creates objects in the database
ALTER – Alters objects of the database
DROP – Deletes objects of the database
TRUNCATE – Deletes all records from a table and resets table identity to initial value.

DCL

DCL is abbreviation of Data Control Language. It is used to create roles, permissions, and referential integrity as well it is used to control access to database by securing it.

GRANT – Gives user’s access privileges to database
REVOKE – Withdraws user’s access privileges to database given with the GRANT command

TCL

TCL is abbreviation of Transactional Control Language. It is used to manage different transactions occurring within a database.

COMMIT – Saves work done in transactions
ROLLBACK – Restores database to original state since the last COMMIT command in transactions

Reference : Pinal Dave (http://blog.SQLAuthority.com), Original Source

Where am I?

You are currently viewing the archives for May, 2009 at Digicorp.