Welcome to Scribd, the world's digital library. Read, publish, and share books and documents. See more
Standard view
Full view
of .
Look up keyword or section
Like this
0 of .
Results for:
No results containing your search query
P. 1
Query Tips

Query Tips

Ratings: (0)|Views: 93|Likes:
Published by sony
This docs tell abt the tricks of sql
This docs tell abt the tricks of sql

More info:

Published by: sony on Dec 31, 2009
Copyright:Attribution Non-commercial


Read on Scribd mobile: iPhone, iPad and Android.
download as DOC, PDF, TXT or read online from Scribd
See more
See less





Q. Execute an Operating System Command From Within SQL Server (Completed 36)
A. The xp_cmdshell extended store procedure makes it possible to execute operating system commandsfrom within SQL Server.Example:EXEC Master..xp_cmdshell 'Dir c:\'
Q. How can I create a plain-text flat file from SQL Server as input to another application?
A. One of the purposes of Extensible Markup Language (XML) is to solve challenges like this, but until allapplications become XML-enabled, consider using our faithful standby, the bulk copy program (bcp) utility.This utility can do more than just dump a table; bcp also can take its input from a view instead of from atable. After you specify a view as the input source, you can limit the output to a subset of columns or to asubset of rows by selecting appropriate filtering (WHERE and HAVING) clauses.More important, by using a view, you can export data from multiple joined tables. The only thingyou cannot do is specify the sequence in which the rows are written to the flat file, because a view does notlet you include an ORDER BY clause in it unless you also use the TOP keyword.If you want to generate the data in a particular sequence or if you cannot predict the content of thedata you want to export, be aware that in addition to a view, bcp also supports using an actual query. Theonly "gotcha" about using a query instead of a table or view is that you must specify queryout in place of outin the bcp command line.For example, you can use bcp to generate from the pubs database a list of authors who reside in Californiaby writing the following code:bcp "SELECT * FROM pubs..authors WHERE state = 'CA'" queryout c:\CAauthors.txt -c -T -S
Q. How can I programmatically detect whether a given connection is blocked?
A. A connection is blocked when it requires an object that another connection has a lock on. You can usethe system stored procedure sp_lock to retrieve information about the current locks in SQL Server, and youcan use the server process ID (SPID) to filter the information that sp_lock returns. To determine whether agiven process is waiting for the release of a locked resource, you can execute the sp_GetBlockInfoprocedure that follows.Note: You must execute the procedure before the timeout.USE master GOCREATE PROCEDURE sp_GetBlockInfo@BlockedSPID as intASIF EXISTS (select *FROM master.dbo.syslockinfoWHERE req_spid = @BlockedSPIDAND req_status = 3)SELECT sli1.req_spid AS SPID,SUBSTRING (u.name, 1, 8) As Mode,DB_NAME(sli1.rsc_dbid) AS [Database],OBJECT_NAME(sli1.rsc_objid) AS [Table],sli1.rsc_Text AS [Resource]FROM master.dbo.syslockinfo sli1JOIN master.dbo.spt_values uON sli1.req_mode + 1 = u.number AND u.type = 'L'JOINmaster.dbo.syslockinfo sli2
ON sli1.rsc_dbid = sli2.rsc_dbidAND sli1.rsc_objid = sli2.rsc_objidAND sli1.rsc_text = sli2.rsc_textWHERE sli2.req_spid = @BlockedSPIDAND sli1.req_status = 1AND sli1.req_spid <> @BlockedSPIDAND sli2.req_status = 3ELSESELECT CAST(1 as int) AS SPID,SUBSTRING ('', 1, 8) AS Mode,DB_NAME(NULL) AS [Database],OBJECT_NAME(NULL) AS [Table],CAST(NULL AS nchar(32)) AS [Resource]WHERE 1=2GOThe sp_GetBlockInfo procedure tells you the lock mode, the database and object names of the lockedresource, and in the case of a blocking chain, which SPID is the root blocker. If the process is not blocked,sp_GetBlockInfo returns an empty recordset.You can also detect blocks by checking for error 1222, "Lock request time out period exceeded."The LOCK_TIMEOUT setting controls how long a process will wait for locks to be released before timingout. When the lock timeout occurs, SQL Server sends error 1222 to the application. In SQL Server 7.0, thiserror aborts the statement but does not cause the batch to roll back, so you can look for the Transact-SQLsystem variable @@ERROR and determine where locks exist 
Q. Can you create UNIQUE and PRIMARY KEY constraints on computed columns in SQL Server 2000?
A. In SQL Server, the physical mechanism that UNIQUE and PRIMARY KEY constraints use to enforceuniqueness is a unique index. Because SQL Server 2000 supports indexes on computed columns,you can create UNIQUE and PRIMARY KEY constraints on computed columns.Defining a UNIQUE constraint on a computed column is a straightforward process, as the following exampleshows:CREATE TABLE T1 (col1 int NOT NULL,col2 AS col1 + 1 UNIQUE)However, if you define a PRIMARY KEY on a computed column, such as:CREATE TABLE T2 (col1 int NOT NULL,col2 AS col1 + 1 PRIMARY KEY)you receive the following error:Server: Msg 8111, Level 16, State 2, Line 1Cannot define PRIMARY KEY constraint on nullable column in table 'T2'.Server: Msg 1750, Level 16, State 1, Line 1Could not create constraint. See previous errors.Because of the primary key constraint, SQL Server requires you to guarantee that your computation'sresult will not be NULL. The computation in the computed column can overflow(for example, when you add 1 to the largest integer) or underflow (when you subtract 1 from the smallestinteger), and other computations can result in a divide-by-zero error. However, if the ARITHABORT(which determines whether a query has ended when an overflow or a divide-by-zero error occurs)
and ANSI_WARNINGS (which specifies ANSI SQL-92 standard behavior for several error conditions)session settings are off, instead of ending the query, the computation can have a NULL result.In practice, when either ARITHABORT or ANSI_WARNINGS settings is off, you cannot create anindex on a computed column or insert values into a table that has an index on a computed column becauseSQL Server detects such an attempt and returns an error. But SQL Server still requires you to guaranteethat the computation will not result in NULL values. The trick is to wrap the computed column's computationwith the ISNULL() function and supply an alternative value if the computation results in NULL:CREATE TABLE T2 (col1 int NOT NULL,col2 AS ISNULL(col1 + 1, 0) PRIMARY KEY)
Q. Why does my inline or embedded SQL run faster than my stored procedures?
A. Recompilations might be the source of the slower stored procedure speed. To find out for sure, you needto do some performance investigation, such as looking at Showplans for each type of query versus callingthe stored procedures and comparing query plan cache hits to cache misses. You can also try coding theobject owner for referenced tables, views, and procedures inside your stored procedures, as the followingexample shows:SELECT * FROM dbo.mytableThis technique helps you reuse plans and prevent cache misses.
Q. Why doesn't SQL Server permit an ORDER BY clause in the definition of a view?
A. SQL Server excludes an ORDER BY clause from a view to comply with the ANSI SQL-92 standard.Because analyzing the rationale for this standard requires a discussion of the underlying structure of thestructured query language (SQL) and the mathematics upon which it is based, we can't fully explain therestriction here. However, if you need to be able to specify an ORDER BY clause in a view, consider usingthe following workaround:USE pubsGOCREATE VIEW AuthorsByNameASSELECT TOP 100 PERCENT *FROM authorsORDER BY au_lname, au_fnameGOThe TOP construct, which Microsoft introduced in SQL Server 7.0, is most useful when you combine it withthe ORDER BY clause. The only time that SQL Server supports an ORDER BY clause in a view is when it isused in conjunction with the TOP keyword.Note that the TOP keyword is a SQL Server extension to the ANSI SQL-92 standard.
Q. Is using the TOP N clause faster than using SET ROWCOUNT N to return a specific number of rows from a query?
A. With proper indexes, the TOP N clause and SET ROWCOUNT N statement are equally fast, but withunsorted input from a heap, TOP N is faster. With unsorted input, the TOP N operator uses a small internalsorted temporary table in which it replaces only the last row. If the input is nearly sorted, the TOP N enginemust delete or insert the last row only a few times. Nearly sorted means you're dealing with a heap withordered inserts for the initial population and without many updates, deletes, forwarding pointers, and so onafterward. A nearly sorted heap is more efficient to sort than sorting a huge table. In a test that used TOP Nto sort a table with the same number of rows but with unordered inserts, TOP N was not as efficientanymore. Usually, the I/O time is the same both with an index and without; however, without an index SQL

Activity (4)

You've already reviewed this. Edit your review.
1 thousand reads
1 hundred reads
webnet liked this
webnet liked this

You're Reading a Free Preview

/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->