Select Syntax Execution In Server Behind..

Apr 21, 2008

Hi All,

I need some help from u..

I wanted to know the exact flow behind SQL Server when we fire

SELECT select_list

[ FROM table_source ]

[ON Join_Condition]

[ WHERE search_condition ]

[ GROUP BY group_by_expression ]

[ HAVING search_condition ]

[ ORDER BY order_expression [ ASC | DESC ] ]

what is exact execution process mean which get first strike to server and then what followed then..

T.I.A

View 3 Replies


ADVERTISEMENT

Correct Syntax For This Select In SQL Server?

Jun 22, 2007

This (demo) statement is fine in Access, and so far as I can see, shouldbe OK in SQL Server.But Enterprise Manager barfs at the final bracket. Can anyone helpplease?select sum(field1) as sum1, sum(field2) as sum2 from(SELECT * from test where id < 3unionSELECT * from test where id 2)In fact, I can reduce it to :-select * from(SELECT * from test)with the same effect - clearly I just need telling :-)cheers,Jim--Jima Yorkshire polymoth

View 4 Replies View Related

Import Export Wizard - Syntax Error In Preview &&amp; Execution

Jan 3, 2008

Source: MS SQL Server 6.5
Destination: MS SQL Server 2005 (SP2 installed)
Suppl Ver Info: Microsoft.SqlServer.MaintenancePlanTasks.dll (ver 9.0.3043.0)


Desc:
When copying one table from source to destination (using import export wizard), the following error shows. However, when using query select * from tbl_1 can shows preview correctly. (but still need to save as SSIS, and change codepage property before it works)


===================================

The preview data could not be retrieved. (SQL Server Import and Export Wizard)

===================================

Line 1: Incorrect syntax near '['. (Microsoft OLE DB Provider for SQL Server)

------------------------------
Program Location:

at System.Data.OleDb.OleDbDataReader.ProcessResults(OleDbHResult hr)
at System.Data.OleDb.OleDbDataReader.NextResult()
at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method)
at System.Data.OleDb.OleDbCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.OleDb.OleDbCommand.System.Data.IDbCommand.ExecuteReader()
at Microsoft.SqlServer.Dts.DtsWizard.Preview.LoadPreview()

When executing the wizard, the following error shows (the table exists, of course)


===================================

Could not connect source component.

Error 0xc0202009: Source - tbl_1[1]: SSIS Error Code DTS_E_OLEDBERROR. An OLE DB error has occurred. Error code: 0x80040E37.


Error 0xc02020e8: Source - tbl_1[1]: Opening a rowset for "[db_1].[sch_1].[tbl_1]" failed. Check that the object exists in the database.
(SQL Server Import and Export Wizard)

===================================

Exception from HRESULT: 0xC02020E8 (Microsoft.SqlServer.DTSPipelineWrap)

------------------------------
Program Location:

at Microsoft.SqlServer.Dts.Pipeline.Wrapper.CManagedComponentWrapperClass.ReinitializeMetaData()
at Microsoft.SqlServer.Dts.DtsWizard.Execute.SetSourceConnection(Exception& ex, TransformInfo ti)




Exception from HRESULT: 0xC02020E8 (Microsoft.SqlServer.DTSPipelineWrap)


Could anybody please kindly help me on that?

View 2 Replies View Related

Report Builder Bug?: Semantic Query Execution Failed. Incorrect Syntax Near 'NULLAND'.

Sep 3, 2007

Hi

I get the following error when running a report in report builder using the Adventureworks sample model:
Semantic query execution failed. Incorrect syntax near 'NULLAND'.----------------------------Query execution failed for data set 'dataSet'.----------------------------An error has occurred during report processing.

Here is how to replicate the error:


Create a table report using the Adventure Works model.
Select Product entity, add Product Category and #Products to the table.
Edit formula for #Products to "COUNT(Products)" and add a filter on Products for "Discontinued Date is empty". (I want a count of products that have not been discontinued).
If you run the report now, it willl work as expected.
Add a report filter for "Product.Color is empty" (I only want to see products that don't have a color)
Run the report to get the above error.
While the above is a contrived example, I am getting the same error on a data model that I am developing for a customer.

Am I missing something, or is this a bug in Report Builder?

Thanks

View 2 Replies View Related

Select Syntax

May 16, 2002

In a select statement select_list, if one of the columns in the result set is NULL, I need to substitute a constant value else I want to return the value in the column. Would I use an IF_THEN_ELSE or CASE expression and how would that look?
Thanks,
Robert

View 3 Replies View Related

ABout SELECT Syntax?

Nov 7, 2006

Hi,everyone.

Today I met with a interesting problem. According to Microsoft SQL SERVER 2005 BOOKS ONLINE, there is following SELECT Syntax:

(1) SELECT @local_variable (Transact-SQL)

For example:

DECLARE @i int
SELECt @i=100

(2) SELECt QUERY statement:

SELECT [ ALL | DISTINCT ]
[ TOP expression [ PERCENT ] [ WITH TIES ] ]
<select_list>
<select_list> ::=
.....

For example,

[AdventureWorks]
SELECT * FROM DatabaseLog


To my surprise, in the given project, I met this kind of SELECT statement,

DECLARE @w_type varchar(10), @i varchar(30)
SELECT @i='3'
SELECT @w_type='OLTPNORMAL' WHERE @i IN ('0','1','2','3','4','5','9',)
SELECT @w_type

The result is:

OLTPNORMAL

However, I have not met with the kind of SELECT statement before. Please give me some advice. Thank you in advance.

View 3 Replies View Related

Syntax For IF-THEN In SQL Select Statement

Sep 3, 2007

I need to use IF-THEN in a SQL Select statement.  Using Google
I have found a couple of obscure references to this but nothing that I
can use.  Tried various combinations without luck.  Can
anyone point me to a good resource or supply a simple example of proper
syntax?  Thanks in advance for any help provided.

View 2 Replies View Related

SQL Syntax With For Select Like Statement

Dec 6, 2007

Hello,
 
I have the following statement that I am trying to convert to a "like" statement in a SqlDataSource for a web application.  I can't seem to get the syntax correct.  Would someone be able to assist with this?  Thanks!
SELECT * FROM [Employees] WHERE ([LName] = @LName) ORDER BY [LName], [FName]
Something like below.
SELECT * FROM [Employees] WHERE ([LName] LIKE '@LName%') ORDER BY [LName], [FName]

View 3 Replies View Related

LIKE Syntax In A SELECT Statement

May 19, 2008

What is the syntax for making a query using like, the below is my code
 <asp:SqlDataSource ID="Search" runat="server"
ConnectionString="<%$ ConnectionStrings:DatabaseConnectionString %>"
ProviderName="<%$ ConnectionStrings:DatabaseConnectionString.ProviderName %>"
SelectCommand="SELECT * FROM [Products]WHERE category LIKE %@category%">
 
<SelectParameters>
<asp:QueryStringParameter Name="category"
QueryStringField="category" Type="string" />
</SelectParameters>
</asp:SqlDataSource>
 Its giving a syntax error but I dont know how to change it.
Please advise, thanks!

View 5 Replies View Related

Select Default Value Syntax

Jan 25, 2006

Hi everyone, I'm looking for a way to select the default value of a particular column but can't seem to find the syntax for this anywhere. It's a rather peculiar situation where it's needed...
Thanks

View 3 Replies View Related

Help W/syntax Select In A While Loop

Aug 31, 2004

I am having trouble with this statement. I am returning multiple rows because I am doing the select statement within the loop. I need to keep the loop somehow because of the where clause of the select statement:

'AND @start not in (select sh_istart from casemas where sh_istart in (select sh_istop from casemas where sh_serial in (53565,53588,53597)))
and @start between sh_istart and sh_istop'

Is there anyway that I can maintain the ability to use the loop but not do mutiple select statements like below:

Also I'm trying really hard not to use temp tables in this example

Result from select statement below

sh_serial
-----------
53565
53597

sh_serial
-----------
53565
53597

sh_serial
-----------

sh_serial
-----------
53588
53597

Desired results:

sh_serial
-----------
53588
53597
53565

Syntax:

declare @start int
select @start = 580
declare @stop int
select @stop = 900

while @start <= @stop
begin
select sh_serial,
from casemas, schilin
WHERE (schi_shser = sh_serial)
and (schi_itemno = '004852')
and (sh_serial <> 600000)
and sh_serial in (53565,53588,53597)
and sh_serial in

(select distinct sh_serial
from casemas, schilin
WHERE (schi_shser = sh_serial)
and (schi_itemno = '004852')
and sh_serial in (53565,53588,53597)
AND @start not in (select sh_istart from casemas where sh_istart in (select sh_istop from casemas where sh_serial in (53565,53588,53597)))
and @start between sh_istart and sh_istop
group by sh_serial
having (sum(schi_qty) + 1 < 4 ))


select @start = @start + 1
end



I'd appreciate any help. Thanks! :o

View 5 Replies View Related

Help With Syntax (select Case)

Mar 4, 2008

Hi,

I looked up select case statements and have used them for returning single values, but can't seem to get it working when returning a select statement..

I have my SPROC configured as below, can anyone help me out as to why its not working?

btw previously I had been using something like below, but in this case it wont work as I have to make more changes than just the WHERE genderID = @genderID (hmm, hopefully that makes sense, if not ignore my example lol)


IF @genderID > 2
..
ELSE
........WHERE genderID = @genderID


thanks very much once again!
mike123



CREATE PROCEDURE [dbo].[select_123]
(
@genderID tinyint
)

AS SET NOCOUNT ON


SELECT

CASE @genderID
WHEN 1 THEN

SELECT TOP 40 *

FROM tbl
WHERE .......


WHEN 2 THEN

SELECT TOP 40 *

FROM tbl
WHERE .......
ELSE
SELECT TOP 40 *

FROM tbl
WHERE .......



END

View 3 Replies View Related

SQL Syntax For Distinct Select

Jul 20, 2005

I'm trying to order a varchar column first numerically, and secondalphanumerically using the following SQL:SELECT distinct doc_numberFROM doc_lineWHERE product_id = 'WD' AND doc_type = 'O'ORDER BY CASE WHEN IsNumeric(doc_number) = 1THEN CONVERT(FLOAT, doc_number)ELSE 999999999END,CASE WHEN IsNumeric(doc_number) = 1THEN 'ZZZZZZZZZ'ELSE doc_numberEND;When try executing this statement, I get the following error:Server: Msg 145, Level 15, State 1, Line 1ORDER BY items must appear in the select list if SELECT DISTINCT isspecified.If I take the "distinct" out, it works just fine, except for the fact that Iget many duplicates.Does anyone have any suggestions?Thanks,Frank

View 3 Replies View Related

SELECT Syntax Question

Sep 22, 2006

Hi,

Simple question:

Is there any way to write this in a shorter form:

SELECT fcol like 'X' or fcol like 'Y' or fcol like 'Z'

Maybe something like (which I know it won't work but just to give you an idea what I am looking for)

SELECT fcol like ('X' or 'Y' or 'Z')


I know of this (Full query), but it doesn't work with WILD card characters

select ftype
from engecnentries
where ftype in ('%cone%','%basin%')

any ideas?

View 5 Replies View Related

MSSQL Select Syntax Help

Jan 16, 2007

I have a table that has unit id, date, time, etc. I would like to select each unit id with the last date it has in the table. The result should have each unit listed once with the latest date in the table.

For Example:

unit id Date Time
00100 01/12/2007 8:00
00100 01/12/2007 8:45
00200 01/12/2007 8:50
00100 01/13/2007 13:30
00300 01/13/2007 13:45
00100 01/14/2007 11:00
00200 01/14/2007 11:30

the result should be:

00100 01/14/2007 11:00
00200 01/14/2007 11:30
00300 01/13/2007 13:45

View 5 Replies View Related

Incorrect Syntax Near The Keyword SELECT

Sep 19, 2007

Hello, I have the following query. When I run the query I get the following error message: "Incorrect syntax near keyword SELECT"--------------------------------------------------- SELECT * FROM (SELECT ROW_NUMBER() OVER(ORDER BY DateAdded) AS rownum, * FROM SELECT     TOP (100) PERCENT Videos.VideoId, Videos.UserId, Videos.UserName, Videos.Title, Videos.Description, Videos.Tags, Videos.VideoLength, Videos.TimesHeard,                       Videos.ImageURL, Videos.RecType, Videos.Language, Videos.Category, Videos.DateAdded, Videos.RewardProgram, Videos.EditorChoice, TB2.hitsFROM         Videos LEFT OUTER JOIN                          (SELECT     TOP (100) PERCENT VideoId, COUNT(*) AS hits                            FROM          (SELECT     TOP (100) PERCENT UserId, VideoId, COUNT(*) AS cnt1                                                    FROM          Hits                                                    GROUP BY VideoId, UserId) AS TB1                            GROUP BY VideoId) AS TB2 ON Videos.VideoId = TB2.VideoIdORDER BY TB2.hits DESC) AS T1WHERE rownum <= 5----------------------------------------- If I run the query that is in BOLD as: SELECT *
FROM (SELECT ROW_NUMBER() OVER(ORDER BY DateAdded) AS rownum, * FROM Videos) AS T1 WHERE rownum <=5the query runs just fine. Also if I run the query that is NOT bold (above), it also runs fine. What can I do to run them both together as seen above? Thank in advance,Louis 

View 4 Replies View Related

Example SQL Syntax To Select Data And Divide

May 7, 2007

I'm trying to help out a beginning DBA and come up with a SQL query. Here is the information I've been given so far.

"I have a SQL database (TEST1_new) with several tables. I need to have some values updated in one of the tables HARR2APP.CUSTOMER_ORDER_LINE_TAB1). I need the value that exists in the QTY_SHIPPED field to be divided by 250. I also need to include a WHERE statement for the PLANNED_SHIP_DATE greater than 11/15/2004 and a CATALOG_NO =18053185292 or 18053185285.

Basically, what I need to do is take the value for QTY_SHIPPED for Catalog_NO 18053185285 & 18053185282 and divide the result by 250"

After reading through her statement above about 10 times and guessing a bit, here's what I was able to come up with. I'm sure the syntax is not correct but maybe it's close to being what's needed?

INSERT INTO HARR2APP.CUSTOMER_ORDER_LINE_TAB1()

(SELECT dbo.TEST1_new.HARR2APP.CUSTOMER_ORDER_LINE_TAB.QTY_SHIPPED LIMIT 1) /250),PLANNED_SHIP_DATE from dbo.TEST1_new.HARR2APP.CUSTOMER_ORDER_LINE_TAB

WHERE CATALOG_NO = ‘18053185292’
OR CATALOG_NO= ‘18053185285’

AND PLANNED_SHIP_DATE > ‘11/15/2004’;

Any help is greatly appreciated.

Chris.

View 4 Replies View Related

Correct Syntax For ADO.net Recordset's Select Method.

Feb 17, 2006

I have a interger stored in x.

I want to use x in a SELECT statement like so :

SELECT * from aTable WHERE A_Column = x

This select statement is then assigned to and passed as a string like :

sql = "SELECT * from aTable WHERE A_Column = x"

How does the x get interpreted correctly ?

View 1 Replies View Related

Syntax To Abandon SELECT On First Occurrence Of Criteria?

Nov 6, 2013

Have a need to scan a large table to see if a set of criteria have ever been met.

If/when the scan hits its first record meeting the criteria, the scan can be abandoned.

Is there some syntax/option that accomplishes this?

Right now, I am doing a SELECT with criteria against the table and the @@ROWCOUNT gives me a zero, or non-zero value.

But that methodology means that the SELECT has to execute against the entirety of the table.

I'd like to abandon the SELECT as soon as it detects a first record meeting the criteria.

View 3 Replies View Related

Transact SQL :: Error Incorrect Syntax Near Keyword Select

Apr 30, 2015

I am getting error "Incorrect syntax near the keyword 'Select'." while running the below query.

DECLARE @DATEPROCESS DATETIME;
SET @DATEPROCESS = CAST(DATEADD(D, -((DATEPART(WEEKDAY, GETDATE()) + 1 + @@DATEFIRST) % 7), GETDATE()) AS DATE)
insert into tempjoin([PART], [SPLRNAME], [SHIPDAYS], [SPRICE]) values
(Select distinct
RC. CAT_PART AS PART, 
RC. CAT_SUPPLIER AS SUPPLIER, 
FFC.[Ships Within Days] AS SHIPDAYS,
ffc.[Sell Price] AS SPRICE

[code]....

View 4 Replies View Related

Nested Select Query Generating Syntax Error

Jan 23, 2008

I hope I'm posting this in the correct forum. If not I apologize. I have a nested select query that I imported from Oracle:

Oracle Version:



Code Snippetselect avg(days) as days from (
select dm_number, max(dm_closedate) - max(comment_closed_date) as days from dm_data
where
dm_type = 'prime' and
dm_closedate <= '31-dec-2007' and
dm_closedate >= '1-dec-2007' and
program = 'aads'
group by dm_number)





SQL Version:



select round(abs(avg(days)), 0) as days from
(select dm.dm_number, abs(datediff(DAY,max(dm.dm_closedate), max(dm.comment_closed_date))) as days
from dm_data dm, ProgramXref px
where
px.Program_Name = 'aads'
and dm.Program_Id = px.Program_Id
and dm.dm_type = 'prime'
and dm.dm_closedate <= '31-dec-2007'
and dm.dm_closedate >= '1-dec-2007'
group by dm.dm_number)





In Oracle the query runs fine. In SQL I am getting a "Line 10: Incorrect syntax near ')'." error. If I run just the nested portion of the query, there are no errors. It only happens when the first query tries to query the nested query. Can anyone help me get the syntax correct?

Thanks,
Lee

View 4 Replies View Related

Stored Procudure With Multiple Select... Incorrect Syntax Near 'storedProcedure'

Mar 8, 2004

Hi,

Im fairly new to writing stored procudures so I thought you lot might be able to help with this problem.

I have a stored procudure which looks like this:

CREATE PROCEDURE usrCienet.spAdminAgencyActivate_Select
(
@strAgencyId CHAR(6)
)

AS

DECLARE @idAgency INT

SELECT @idAgency = idAgency FROM tblAgencies WHERE strAgencyId = @strAgencyId;

SELECT strName, strAddress1, strAddress2, strCounty, strCountry, strPostcode, strTelephone, strFax, bitActive, bitHeadOffice, bitFinanceBranch
FROM tblBranches
WHERE fk_idAgency = @idAgency

SELECT strFirstName, strSurname, strUsername, bitActive
FROM tblUsers
WHERE fk_idAgency = @idAgency

GO

It basically first declare's and sets @idAgency using the first small select statment, then uses that parameter to run two more selects queries which I want sending to a dataset. Now within the Query Analyzer this works fine. But in my asp.net page it trows up this error:

Exception Details: System.Data.SqlClient.SqlException: Line 1: Incorrect syntax near 'spAdminAgencyActivate_Select'

Now the code im using in the asp.net page is as follows:


Dim objSqlConnection as New SqlConnection(ConfigurationSettings.AppSettings("strCon"))
Dim objSqlCommand_Select as New SqlCommand("spAdminAgencyActivate_Select", objSqlConnection)

objSqlCommand_Select.Parameters.Add(New SqlParameter("@strAgencyId", SqlDbType.Char, 6))
objSqlCommand_Select.Parameters("@strAgencyId").Value = "tes001"

Dim objSqlDataAdapter as New SqlDataAdapter(objSqlCommand_Select)

Dim dsActivateAgency as New DataSet()

objSqlConnection.Open()
objSqlDataAdapter.TableMappings.Add("Table", "tblBranches")
objSqlDataAdapter.TableMappings.Add("Table1", "tblUsers")
objSqlDataAdapter.Fill(dsActivateAgency)
objSqlConnection.Close()


Can anyone help? I believe the error is in the stored procedure somewhere, because if I change the stored procedure so no parameters are being passed to it then it starts working. This is what I comment out and change for it to to get it working, but obviously this is not satisfactory as a final result because the parameter is hard coded in the stored procedure. Im just showing this to see if it gives anyone a clue!!

CREATE PROCEDURE usrCienet.spAdminAgencyActivate_Select
--(
--@strAgencyId CHAR(6)
--)

AS

--DECLARE @idAgency INT

--SELECT @idAgency = idAgency FROM tblAgencies WHERE strAgencyId = @strAgencyId;

SELECT strName, strAddress1, strAddress2, strCounty, strCountry, strPostcode, strTelephone, strFax, bitActive, bitHeadOffice, bitFinanceBranch
FROM tblBranches
WHERE fk_idAgency = 1

SELECT strFirstName, strSurname, strUsername, bitActive
FROM tblUsers
WHERE fk_idAgency = 1

GO

Thanks in advance for any help!!

- Carl S

View 1 Replies View Related

SELECT Query Syntax To Display Only The Top Record For Duplicate Records

Oct 6, 2005

Good day!

I just can't figure out how I can display only the top record for the duplicate records in my table.

Example:

Table1
Code Date
01 10/1/05
01 10/2/05
01 10/3/05
02 9/9/05
02 9/9/05
02 9/10/05

My desired result would be:
Table1
Code Date
01 10/1/05
02 9/9/05

Thanks.

View 12 Replies View Related

Left Join Vs Left Outer Join Syntax Generates Different Execution Plans

Apr 16, 2008



Anyone know why using

SELECT *
FROM a LEFT OUTER JOIN b
ON a.id = b.id
instead of

SELECT *
FROM a LEFT JOIN b
ON a.id = b.id

generates a different execution plan?

My query is more complex, but when I change "LEFT OUTER JOIN" to "LEFT JOIN" I get a different execution plan, which is absolutely baffling me! Especially considering everything I know and was able to research essentially said the "OUTER" is implied in "LEFT JOIN".

Any enlightenment is very appreciated.

Thanks

View 5 Replies View Related

In Code Behind, What Is Proper Select Statement Syntax To Retrieve The @BName Field From A Table?

Apr 8, 2006

In Code Behind, What is proper select statement syntax to retrieve the @BName field from a table?Using Visual Studio 2003SQL Server DB
I created the following parameter:Dim strName As String        Dim parameterBName As SqlParameter = New SqlParameter("@BName", SqlDbType.VarChar, 50)        parameterBName.Value = strName        myCommand.Parameters.Add(parameterBName)
I tried the following but get error:Dim strSql As String = "select @BName from Borrower where BName= DOROTHY V FOWLER "
error is:Line 1: Incorrect syntax near 'V'. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Line 1: Incorrect syntax near 'V'.
Source Error:
Line 59: Line 60: Line 61:         myCommand.ExecuteNonQuery()   'Execute the query

View 2 Replies View Related

Incorrect Syntax Near The Keyword 'SELECT'.Incorrect Syntax Near The Keyword 'else'.

May 22, 2008

What I am trying to create a query to check, If recDT is not value or null, then will use value from SELECT top 1 recDtim FROM Serv. Otherwise, will use the value from recDT. I have tried the below query but it doesn't work. The error says, Incorrect syntax near the keyword 'SELECT'.Incorrect syntax near the keyword 'else'.1 SELECT
2 case when recDT='' then SELECT top 1 recDtim FROM Serv else recDT end
3 FROM abc
4
Anyone can help? Thanks a lot.

View 5 Replies View Related

Static Variables In A SQLCLR Stored Proc Seem To Get Reused From Execution To Execution Of The Sp

Aug 23, 2007

after moving off VS debugger and into management studio to exercise our SQLCLR sp, we notice that the 2nd execution gets an error suggesting that our static SqlCommand object is getting reused from the 1st execution (of the sp under mgt studio). If this is expected behavior, we have no problem limiting our statics to only completely reusable objects but would first like to know if this is expected? Is the fact that debugger doesnt show this behavior also expected?

View 4 Replies View Related

Execution Plans &<&> Proportionate Execution Times

Dec 7, 2005

Hi I am slowly getting to grips with SQL Server. As a part of this, I have been attempting to work on producing more efficient queries. This post is regarding what appears to be a discrepancy between the SQL Server execution plan and the actual time taken by a query to run. My brief is to produce an attendance system for an education establishment (I presume you know I'm not an A-Level student completing a project :p ). Circa 1.5m rows per annum, testing with ~3m rows currently. College_Year could strictly be inferred from the AttDateTime however it is included as a field because it a part of just about every PK this table is ever likely to be linked to. Indexes are not fully optimised yet. Table:CREATE TABLE [dbo].[AttendanceDets] ([College_Year] [smallint] NOT NULL ,[Group_Code] [char] (12) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,[Student_ID] [char] (8) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,[Session_Date] [datetime] NOT NULL ,[Start_Time] [datetime] NOT NULL ,[Att_Code] [char] (1) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ) ON [PRIMARY]GO CREATE CLUSTERED INDEX [IX_AltPK_Clust_AttendanceDets] ON [dbo].[AttendanceDets]([College_Year], [Group_Code], [Student_ID], [Session_Date], [Att_Code]) ON [PRIMARY]GO CREATE INDEX [All] ON [dbo].[AttendanceDets]([College_Year], [Group_Code], [Student_ID], [Session_Date], [Start_Time], [Att_Code]) ON [PRIMARY]GO CREATE INDEX [IX_AttendanceDets] ON [dbo].[AttendanceDets]([Att_Code]) ON [PRIMARY]GOALL inserts are via an overnight sproc - data comes from a third party system. Group_Code is 12 chars (no more no less), student_ID 8 chars (no more no less). I have created a simple sproc. I am using this as a benchmark against which I am testing my options. I appreciate that this sproc is an inefficient jack of all trades - it has been designed as such so I can compare its performance to more specific sprocs and possibly some dynamic SQL. Sproc:CREATE PROCEDURE [dbo].[CAMsp_Att] @College_Year AS SmallInt,@Student_ID AS VarChar(8) = '________', @Group_Code AS VarChar(12) = '____________', @Start_Date AS DateTime = '1950/01/01', @End_Date as DateTime = '2020/01/01', @Att_Code AS VarChar(1) = '_' AS IF @Start_Date = '1950/01/01'SET @Start_Date = CAST(CAST(@College_Year AS Char(4)) + '/08/31' AS DateTime) IF @End_Date = '2020/01/01'SET @End_Date = CAST(CAST(@College_Year +1 AS Char(4)) + '/07/31' AS DateTime) SELECT College_Year, Group_Code, Student_ID, Session_Date, Start_Time, Att_Code FROM dbo.AttendanceDets WHERE College_Year = @College_YearAND Group_Code LIKE @Group_CodeAND Student_ID LIKE @Student_IDAND Session_Date <= @End_DateAND Session_Date >=@Start_DateAND Att_Code LIKE @Att_CodeGOMy confusion lies with running the below script with Show Execution Plan:--SET SHOWPLAN_TEXT ON--Go DECLARE @Time as DateTime Set @Time = GetDate() select College_Year, group_code, Student_ID, Session_Date, Start_Time, Att_Code from attendanceDetswhere College_Year = 2005 AND group_code LIKE '____________' AND Student_ID LIKE '________'AND Session_Date <= '2005-11-16' AND Session_Date >= '2005-11-16' AND Att_Code LIKE '_' Print 'First query took: ' + CAST(DATEDIFF(ms, @Time, GETDATE()) AS VarCHar(5)) + ' milli-Seconds' Set @Time = GetDate() EXEC CAMsp_Att @College_Year = 2005, @Start_Date = '2005-11-16', @End_Date = '2005-11-16' Print 'Second query took: ' + CAST(DATEDIFF(ms, @Time, GETDATE()) AS VarCHar(5)) + ' milli-Seconds'GO --SET SHOWPLAN_TEXT OFF--GOThe execution plan for the first query appears miles more costly than the sproc yet it is effectively the same query with no parameters. However, my understanding is the cached plan substitutes literals for parameters anyway. In any case - the first query cost is listed as 99.52% of the batch, the sproc 0.48% (comparing the IO, cpu costs etc support this). BUT the text output is:(10639 row(s) affected) First query took: 596 milli-Seconds (10639 row(s) affected) Second query took: 2856 milli-SecondsI appreciate that logical and physical performance are not one and the same but can why is there such a huge discrepancy between the two? They are tested on a dedicated test server, and repeated running and switching the order of the queries elicits the same results. Sample data can be provided if requested but I assumed it would not shed much light. BTW - I know that additional indexes can bring the plans and execution time closer together - my question is more about the concept. If you've made it this far - many thanks.If you can enlighten me - infinite thanks.

View 10 Replies View Related

Execution Procedure Stored During Execution Of The Report .

Aug 3, 2007



Hello :

How to execute a procedure stored during execution of the report, that is before the poster the data.

Thnak you.

View 4 Replies View Related

Execution In Scheduled Job Vs Direct Execution

Nov 29, 2004

Here's my case, I have written a stored procedure which will perform the following:
1. Grab data from a table using cursor,
2. Process data,
3. Write the result into another table

If I execute the stored procedure directly (thru VS.NET, or Query Analyser), it will run, but when I tried to execute it via a scheduled job, it fails.

I used the same record, same parameters, and the same statements to call the stored procedure.

Any idea?

View 3 Replies View Related

Incorrect Syntax Near The Keyword CONVERT When The Syntax Is Correct - Why?

May 20, 2008

Why does the following call to a stored procedure get me this error:


Msg 156, Level 15, State 1, Line 1

Incorrect syntax near the keyword 'CONVERT'.




Code Snippet

EXECUTE OpenInvoiceItemSP_RAM CONVERT(DATETIME,'01-01-2008'), CONVERT(DATETIME,'04/30/2008') , 1,'81350'




The stored procedure accepts two datetime parameters, followed by an INT and a varchar(10) in that order.

I can't find anything wrong in the syntax for CONVERT or any nearby items.


Help me please. Thank you.

View 7 Replies View Related

Incorrect Syntax When There Appears To Be No Syntax Errors.

Dec 14, 2003

I keep receiving the following error whenever I try and call this function to update my database.

The code was working before, all I added was an extra field to update.

Exception Details: System.Data.SqlClient.SqlException: Incorrect syntax near the keyword 'WHERE'


Public Sub MasterList_Update(sender As Object, e As DataListCommandEventArgs)

Dim strProjectName, txtProjectDescription, intProjectID, strProjectState as String
Dim intEstDuration, dtmCreationDate, strCreatedBy, strProjectLead, dtmEstCompletionDate as String

strProjectName = CType(e.Item.FindControl("txtProjectName"), TextBox).Text
txtProjectDescription = CType(e.Item.FindControl("txtProjDesc"), TextBox).Text
strProjectState = CType(e.Item.FindControl("txtStatus"), TextBox).Text
intEstDuration = CType(e.Item.FindControl("txtDuration"), TextBox).Text
dtmCreationDate = CType(e.Item.FindControl("txtCreation"),TextBox).Text
strCreatedBy = CType(e.Item.FindControl("txtCreatedBy"),TextBox).Text
strProjectLead = CType(e.Item.FindControl("txtLead"),TextBox).Text
dtmEstCompletionDate = CType(e.Item.FindControl("txtComDate"),TextBox).Text
intProjectID = CType(e.Item.FindControl("lblProjectID"), Label).Text

Dim strSQL As String
strSQL = "Update tblProject " _
& "Set strProjectName = @strProjectName, " _
& "txtProjectDescription = @txtProjectDescription, " _
& "strProjectState = @strProjectState, " _
& "intEstDuration = @intEstDuration, " _
& "dtmCreationDate = @dtmCreationDate, " _
& "strCreatedBy = @strCreatedBy, " _
& "strProjectLead = @strProjectLead, " _
& "dtmEstCompletionDate = @dtmEstCompletionDate, " _
& "WHERE intProjectID = @intProjectID"

Dim myConnection As New SqlConnection(System.Configuration.ConfigurationSettings.AppSettings("connectionstring"))
Dim cmdSQL As New SqlCommand(strSQL, myConnection)

cmdSQL.Parameters.Add(new SqlParameter("@strProjectName", SqlDbType.NVarChar, 40))
cmdSQL.Parameters("@strProjectName").Value = strProjectName
cmdSQL.Parameters.Add(new SqlParameter("@txtProjectDescription", SqlDbType.NVarChar, 30))
cmdSQL.Parameters("@txtProjectDescription").Value = txtProjectDescription
cmdSQL.Parameters.Add(new SqlParameter("@strProjectState", SqlDbType.NVarChar, 30))
cmdSQL.Parameters("@strProjectState").Value = strProjectState
cmdSQL.Parameters.Add(new SqlParameter("@intEstDuration", SqlDbType.NVarChar, 60))
cmdSQL.Parameters("@intEstDuration").Value = intEstDuration
cmdSQL.Parameters.Add(new SqlParameter("@dtmCreationDate", SqlDbType.NVarChar, 15))
cmdSQL.Parameters("@dtmCreationDate").Value = dtmCreationDate
cmdSQL.Parameters.Add(new SqlParameter("@strCreatedBy", SqlDbType.NVarChar, 10))
cmdSQL.Parameters("@strCreatedBy").Value = strCreatedBy
cmdSQL.Parameters.Add(new SqlParameter("@strProjectLead", SqlDbType.NVarChar, 15))
cmdSQL.Parameters("@strProjectLead").Value = strProjectLead
cmdSQL.Parameters.Add(new SqlParameter("@dtmEstCompletionDate", SqlDbType.NVarChar, 24))
cmdSQL.Parameters("@dtmEstCompletionDate").Value = dtmEstCompletionDate
cmdSQL.Parameters.Add(new SqlParameter("@intProjectID", SqlDbType.NChar, 5))
cmdSQL.Parameters("@intProjectID").Value = intProjectID

myConnection.Open()
cmdSQL.ExecuteNonQuery
myConnection.Close()

MasterList.EditItemIndex = -1
BindMasterList()


End Sub

Thankyou in advance.

View 3 Replies View Related

Which Is Faster? Conditional Within JOIN Syntax Or WHERE Syntax?

Mar 31, 2008

Forgive the noob question, but i'm still learning SQL everyday and was wondering which of the following is faster? I'm just gonna post parts of the SELECT statement that i've made changes to:

INNER JOIN Facilities f ON e.Facility = f.FacilityID AND f.Name = @FacilityName

OR

WHERE f.Name = @FacilityName


My question is whether or not the query runs faster if i put the condition within the JOIN line as opposed to putting in the WHERE line? Both ways seems to return the same results but the time difference between methods is staggering? Putting the condition within the JOIN line makes the query run about 3 times faster?

Again, forgive my lack of understanding, but could someone agree or disagree and give me the cliff-notes version of why or why not?

Thanks!

View 4 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved