Showing posts with label query. Show all posts
Showing posts with label query. Show all posts

Friday, March 30, 2012

How to execute a dynamic SQL with integer parameter for stored procedure?

I'm having problem on trying to execute a query in stored procedure that has parameters as a integer. The parameter with the integer is in the WHERE clause. If I take out the WHERE clause, it would work. If I take out the parameter and replace it with a value, it would work. I have try using the CONVERT function to convert it to an integer, still no luck.

Error: Unterminated String Constant.

What is the problem?

Set @.strSQL='Select *
From
(
SELECT Row_Number() Over(Order By '+ @.SortExpression+') as Row_Count,Rank() Over (Order By '+ @.SortExpression+') as TableInfo_ColumnSort,dbo.EVENT_LOGS.EVENTLOG_ID, dbo.USERS.USERNAME, dbo.EVENT_LOGS.ITEM_TYPE, dbo.EVENT_LOGS.SCREEN_ID,
dbo.EVENT_LOGS.CHANGE_TYPE, dbo.EVENT_LOGS.IP_ADDRESS, dbo.EVENT_LOGS.CREATE_DATE,dbo.USERS.FIRST_NAME,dbo.USERS.Last_NAME
FROM dbo.EVENT_LOGS INNER JOIN
dbo.USERS ON dbo.EVENT_LOGS.USER_UID = dbo.USERS.USERID
) as TableInfo
Where Row_Count Between '+@.startRowIndex+' and '+ @.maxRowIndex+' ';
Exec(@.strSQL);

Can you please try:

Where Row_Count Between ' +Convert(Varchar,@.startRowIndex)+' and '+Convert(Varchar,@.maxRowIndex)+''

|||

Try

Set @.strSQL='Select *
From
(
SELECT Row_Number() Over(Order By ' + @.SortExpression + ') as Row_Count,Rank() Over (Order By ' + @.SortExpression + ') as TableInfo_ColumnSort,dbo.EVENT_LOGS.EVENTLOG_ID, dbo.USERS.USERNAME, dbo.EVENT_LOGS.ITEM_TYPE, dbo.EVENT_LOGS.SCREEN_ID,
dbo.EVENT_LOGS.CHANGE_TYPE, dbo.EVENT_LOGS.IP_ADDRESS, dbo.EVENT_LOGS.CREATE_DATE,dbo.USERS.FIRST_NAME,dbo.USERS.Last_NAME
FROM dbo.EVENT_LOGS INNER JOIN
dbo.USERS ON dbo.EVENT_LOGS.USER_UID = dbo.USERS.USERID
) as TableInfo
Where Row_Count Between ' +CONVERT(VARCHAR(10),@.startRowIndex) -- the integer needs to be converted to varchar for the + to be a concatenate!
+ ' and ' +CONVERT(VARCHAR(10),@.maxRowIndex) + ' ';
PRINT @.strSQL -- Comment this out once the TSQL is generated correctly
Exec(@.strSQL);

|||

It works! I was converting it to an integer with the convert function. I didn't realized I had to convert it as a string..

how to execute (using sp_executesql or other...) heterogeneous dyn

use SET ANSI_NULLS ON and SET ANSI_WARNINGS ON in dynamic query
"herve maillarda" wrote:

> Hi,
> I need to run execute an heterogeneous dynamic query (I build the query
> using nvarchar variable).
> Code sample :
> CREATE PROCEDURE COPY_DATA (@.ServerName nvarchar(20), @.DbName
> nvarchar(20),@.TableName nvarchar(20), @.DateDeb DateTime, @.DateFin
> DateTime) AS
> -- Build SQL Query --
> Set @.Ch_SQL = +"INSERT INTO " + @.ServerName + "." + @.DbName + ".dbo." +
> @.TableName + " ( Date_Heure, Valeur )"
> Set @.Ch_SQL =@.Ch_SQL + " SELECT Date_Heure,Valeur FROM " + @.DbName +
> ".dbo." + @.TableName + " WHERE (Date_Heure >= CONVERT(DATETIME, '" +
> CAST(@.DateDeb AS nvarchar(20)) + "', 102) AND Date_Heure <=
> CONVERT(DATETIME, '" + CAST(@.DateFin AS nvarchar(20)) +"', 102))"
> -- Execute query
> SET ANSI_NULLS ON
> SET ANSI_WARNINGS ON
> exec sp_executesql @.Ch_SQL
> GO
>
> I've alway an error coming from SQL server..."You must set ANSI_NULLS
> and ANSI_WARNINGS"...
> If I try the query from the Analyzer it works ...
> How can I do ?
> Thanks for your help...
> Herve.
> *** Sent via Developersdex http://www.examnotes.net ***
> Don't just participate in USENET...get rewarded for it!
>Won't work...
I still have the same error message coming from the Query Analyzer
"[Microsoft][ODBC SQL Server Driver][SQL Server] heterogeneous querys
require ANSI_NULLS options and ANSI_WARNINGS to be defined for the
connection."
I've try to add the options in my query (as you told me) :
Set @.Ch_SQL = "SET ANSI_NULLS ON SET ANSI_WARNINGS ON INSERT INTO " +
@.ServerName ...
Do I miss something ?
thanks for your help.
Herve MAILLARD
*** Sent via Developersdex http://www.examnotes.net ***
Don't just participate in USENET...get rewarded for it!|||Hi
Do you have triggers that have not had the settings correctly defined?
http://groups-beta.google.com/group...br />
915f7f68
John
Herve MAILLARD wrote:
> Won't work...
> I still have the same error message coming from the Query Analyzer
> "[Microsoft][ODBC SQL Server Driver][SQL Server] heterogeneous querys
> require ANSI_NULLS options and ANSI_WARNINGS to be defined for the
> connection."
> I've try to add the options in my query (as you told me) :
> Set @.Ch_SQL = "SET ANSI_NULLS ON SET ANSI_WARNINGS ON INSERT INTO "
+
> @.ServerName ...
> Do I miss something ?
> thanks for your help.
>
> Herve MAILLARD
> *** Sent via Developersdex http://www.examnotes.net ***
> Don't just participate in USENET...get rewarded for it!sql

How to Execute

My Question:

If we execute Query (Text Format), Im getting Insert statements in result set

Right Now; I'm doing, Copy and Paste the result set in Query window and again running the query to insert into Table.

Is there any way, to execute it Dynamically(instead of copy & paste)

can Any one help with this.

Look into this query:

SET NOCOUNT ON

USE PUBS
GO

Drop Table ##Temp1
GO
Create Table ##Temp1 ( X Varchar (22), Name Varchar (30), Z Varchar (30))

Insert into ##Temp1
select 'select count(*) from ' AS X, Name AS Y, 'Insert into ##1' AS Z
from sysobjects where xtype = 'u'
order by name

-- SELECT * FROM ##Temp1

Drop Table ##1
go
Create Table ##1(Table_Name Varchar(50), No_Of_Rows Int)

select Z + char(10) + 'Select '+ '"' + A.Name + '" ' + 'As Table_Name, ' +
'count(*) As No_of_Rows from '+ A.Name
from sysobjects A , ##Temp1 B
where A.Name = B.Name and xtype = 'U'
order by A.NameEXECUTE should execute your SQL statement

How to exec SQL user defined function?

Hi,
How to exec a SQL user defined function in query analyzer when it accepts parameters.. I know for a stored procedure we can write
EXEC nameofstored procedure abc (@.abc is the parameter passed).. But How to run a SQL function ?
Thanks

assume function GetUser takes ID as input parameter , write the following in query analyzer and execute

BEGIN
DECLARE @.ID int
set @.ID = 45
SELECT dbo.GetUser(@.ID) AS 'User Name'
END

|||You need to either use it in a stored procedure and then call thestored procedure, or use it in some other statement, such as a SELECTstatement:
SELECT MyFunc(someField) FROM MyTable
There's no way to call it directly as you want.
Don
sql

how to excluded the intersection of 2 dimensions ?

Hi,

I have the following simplified problem.

I have a fact table and two dimension tables, colors and weekdays.

I can make a query to select all except red and all except on monday but I like to make a query to select all except red mondays ?

They query tool doesn't give you really the options.

Any suggestions ?

Constantijn Enders

You can do it in MDX, but only a few query tools will allow you to construct queries like this. I think vendors tend to refer to this capability as 'asymmetic sets'; I can only think of one tool I've seen recently that did this (Intelligencia - http://www.it-workplace.co.uk/i4wfeatures.aspx) but I'm sure that if you hunt around there will be others. Does anyone else know of one?

Here's an MDX query to prove it's possible:

select

measures.[internet sales amount] on 0,

except(

[Date].[Day Name].[Day Name].members

*

[Product].[Color].[Color].members

,{([Date].[Day Name].&[2], [Product].[Color].&[Red])}

) on 1

from [Adventure Works]

HTH,

Chris

How to exclude the collation property when scripting a table in SQL Server 2005

In Sequel Server 2000 when I used to script the creation of a table, it was
possible to go to the scripting options in SQL Query Analyser and switch off
the Include Collation statements.
However, I cannot seem to find this setting in SQL Server 2005 - can anyone
point me in the right direction as I do not want to include these statements
when I create a CREATE TABLE script.
Thanks in advance
AndyHi Andrew
If you use the scripting wizard there are configurable options that by
default do not include collations. Try right clicking on the management
branch rather than the table and choose the General Scripts option.
John
"Andrew Houghton" wrote:
> In Sequel Server 2000 when I used to script the creation of a table, it was
> possible to go to the scripting options in SQL Query Analyser and switch off
> the Include Collation statements.
> However, I cannot seem to find this setting in SQL Server 2005 - can anyone
> point me in the right direction as I do not want to include these statements
> when I create a CREATE TABLE script.
> Thanks in advance
> Andy
>
>

Wednesday, March 28, 2012

How to estimate SQL database growth when new fields are added?

I need help regarding calculation of database size growth. Here is my
query:
Q1 We have created two SQL databases, databaseA and databaseB; they are
mirror images of a databaseC which is a non - SQL database.
DatabaseB has been altered to accomodate 3-4 new fields. We need to
estimate how much databaseB grew by. Please note that number of rows
and tables have remained same for both databaseB and databaseC. What
would be the best estimation technique?
We tried database size, in properties but results are very weird.
Any suggestion would be highly appreciated.
Thank you,
AnjaliUse Windows Explorer, and compare DatabaseA files with DatabaseB files. The
File size difference (reported by the OS) should be a matter of subtraction.
--
Arnie Rowland, Ph.D.
Westwood Consulting, Inc
Most good judgment comes from experience.
Most experience comes from bad judgment.
- Anonymous
You can't help someone get up a hill without getting a little closer to the
top yourself.
- H. Norman Schwarzkopf
"Anjali" <anjali.bisht@.gmail.com> wrote in message
news:1162533985.274091.33370@.k70g2000cwa.googlegroups.com...
>I need help regarding calculation of database size growth. Here is my
> query:
> Q1 We have created two SQL databases, databaseA and databaseB; they are
> mirror images of a databaseC which is a non - SQL database.
> DatabaseB has been altered to accomodate 3-4 new fields. We need to
> estimate how much databaseB grew by. Please note that number of rows
> and tables have remained same for both databaseB and databaseC. What
> would be the best estimation technique?
>
> We tried database size, in properties but results are very weird.
> Any suggestion would be highly appreciated.
> Thank you,
> Anjali
>|||I am not sure i can see SQL database in windows explorer. I have
already checked database sizes through SQL enterprise manager, but i am
not satisfied with results.
Is there any other solution?
Arnie Rowland wrote:
> Use Windows Explorer, and compare DatabaseA files with DatabaseB files. The
> File size difference (reported by the OS) should be a matter of subtraction.
> --
> Arnie Rowland, Ph.D.
> Westwood Consulting, Inc
> Most good judgment comes from experience.
> Most experience comes from bad judgment.
> - Anonymous
> You can't help someone get up a hill without getting a little closer to the
> top yourself.
> - H. Norman Schwarzkopf
>
> "Anjali" <anjali.bisht@.gmail.com> wrote in message
> news:1162533985.274091.33370@.k70g2000cwa.googlegroups.com...
> >I need help regarding calculation of database size growth. Here is my
> > query:
> >
> > Q1 We have created two SQL databases, databaseA and databaseB; they are
> > mirror images of a databaseC which is a non - SQL database.
> >
> > DatabaseB has been altered to accomodate 3-4 new fields. We need to
> > estimate how much databaseB grew by. Please note that number of rows
> > and tables have remained same for both databaseB and databaseC. What
> > would be the best estimation technique?
> >
> >
> > We tried database size, in properties but results are very weird.
> >
> > Any suggestion would be highly appreciated.
> > Thank you,
> > Anjali
> >|||Of course you can see the database files using Windows Explorer. Unless you
don't have permissions to the OS level of the server. IF that is the
situation, then ask your admin for assistance.
You can calculate the 'estimated' size increase by adding the datatype
storage requirements for the four new fields, and multiplying that by the
total number of rows in the table. If any of the four new columns are
indexed, the effect of indexing is not included.
--
Arnie Rowland, Ph.D.
Westwood Consulting, Inc
Most good judgment comes from experience.
Most experience comes from bad judgment.
- Anonymous
You can't help someone get up a hill without getting a little closer to the
top yourself.
- H. Norman Schwarzkopf
"Anjali" <anjali.bisht@.gmail.com> wrote in message
news:1162550620.309751.37790@.m7g2000cwm.googlegroups.com...
>I am not sure i can see SQL database in windows explorer. I have
> already checked database sizes through SQL enterprise manager, but i am
> not satisfied with results.
> Is there any other solution?
> Arnie Rowland wrote:
>> Use Windows Explorer, and compare DatabaseA files with DatabaseB files.
>> The
>> File size difference (reported by the OS) should be a matter of
>> subtraction.
>> --
>> Arnie Rowland, Ph.D.
>> Westwood Consulting, Inc
>> Most good judgment comes from experience.
>> Most experience comes from bad judgment.
>> - Anonymous
>> You can't help someone get up a hill without getting a little closer to
>> the
>> top yourself.
>> - H. Norman Schwarzkopf
>>
>> "Anjali" <anjali.bisht@.gmail.com> wrote in message
>> news:1162533985.274091.33370@.k70g2000cwa.googlegroups.com...
>> >I need help regarding calculation of database size growth. Here is my
>> > query:
>> >
>> > Q1 We have created two SQL databases, databaseA and databaseB; they are
>> > mirror images of a databaseC which is a non - SQL database.
>> >
>> > DatabaseB has been altered to accomodate 3-4 new fields. We need to
>> > estimate how much databaseB grew by. Please note that number of rows
>> > and tables have remained same for both databaseB and databaseC. What
>> > would be the best estimation technique?
>> >
>> >
>> > We tried database size, in properties but results are very weird.
>> >
>> > Any suggestion would be highly appreciated.
>> > Thank you,
>> > Anjali
>> >
>sql

How to estimate query governor cost setting?

To prevent a test (which can poorly written) query for running too long that
exhausts my desktop, how I can prevent it from happening? I am thinking of
setting a limit, which I can tolerate a 4 minutes window but not longer than
that.
If this helps: On the properties of "Use query governor to prevent queries
exceeding specified cost", I need to set the cost, but don't know how much.
Thanks.Hi
From BOL:
query governor cost limit Option
Use the query governor cost limit option to specify an upper limit for the
time in which a query can run. Query cost refers to the estimated elapsed
time, in seconds, required to execute a query on a specific hardware
configuration.
Regards
Mike
"C TO" wrote:

> To prevent a test (which can poorly written) query for running too long th
at
> exhausts my desktop, how I can prevent it from happening? I am thinking of
> setting a limit, which I can tolerate a 4 minutes window but not longer th
an
> that.
> If this helps: On the properties of "Use query governor to prevent queries
> exceeding specified cost", I need to set the cost, but don't know how much
.
> Thanks.|||Dear Mike,
Thanks but sorry for my confusing question. I still don't know what the BOL
means by that. I do not know how to estimate the cost limitation I need to
set.
"Mike Epprecht (SQL MVP)" wrote:
[vbcol=seagreen]
> Hi
> From BOL:
> query governor cost limit Option
> Use the query governor cost limit option to specify an upper limit for the
> time in which a query can run. Query cost refers to the estimated elapsed
> time, in seconds, required to execute a query on a specific hardware
> configuration.
> Regards
> Mike
> "C TO" wrote:
>|||Hi
If you want to limit the query to 4 minutes, (4x60 = 240), so put 240 in the
setting box.
Instead of aborting the query, rather look at why it is not performaing well
.
Look at http://www.sql-server-performance.com
Regards
Mike
"C TO" wrote:
[vbcol=seagreen]
> Dear Mike,
> Thanks but sorry for my confusing question. I still don't know what the B
OL
> means by that. I do not know how to estimate the cost limitation I need to
> set.
> "Mike Epprecht (SQL MVP)" wrote:
>|||C TO wrote:
> To prevent a test (which can poorly written) query for running too
> long that exhausts my desktop, how I can prevent it from happening? I
> am thinking of setting a limit, which I can tolerate a 4 minutes
> window but not longer than that.
> If this helps: On the properties of "Use query governor to prevent
> queries exceeding specified cost", I need to set the cost, but don't
> know how much.
> Thanks.
You could also set a query timeout from Query Analyzer or your
application for 4,000ms which forces the command to abort if it's not
completed within the allotted time.
David Gugick
Imceda Software
www.imceda.com

How to estimate query governor cost setting?

To prevent a test (which can poorly written) query for running too long that
exhausts my desktop, how I can prevent it from happening? I am thinking of
setting a limit, which I can tolerate a 4 minutes window but not longer than
that.
If this helps: On the properties of "Use query governor to prevent queries
exceeding specified cost", I need to set the cost, but don't know how much.
Thanks.Hi
From BOL:
query governor cost limit Option
Use the query governor cost limit option to specify an upper limit for the
time in which a query can run. Query cost refers to the estimated elapsed
time, in seconds, required to execute a query on a specific hardware
configuration.
Regards
Mike
"C TO" wrote:
> To prevent a test (which can poorly written) query for running too long that
> exhausts my desktop, how I can prevent it from happening? I am thinking of
> setting a limit, which I can tolerate a 4 minutes window but not longer than
> that.
> If this helps: On the properties of "Use query governor to prevent queries
> exceeding specified cost", I need to set the cost, but don't know how much.
> Thanks.|||Dear Mike,
Thanks but sorry for my confusing question. I still don't know what the BOL
means by that. I do not know how to estimate the cost limitation I need to
set.
"Mike Epprecht (SQL MVP)" wrote:
> Hi
> From BOL:
> query governor cost limit Option
> Use the query governor cost limit option to specify an upper limit for the
> time in which a query can run. Query cost refers to the estimated elapsed
> time, in seconds, required to execute a query on a specific hardware
> configuration.
> Regards
> Mike
> "C TO" wrote:
> > To prevent a test (which can poorly written) query for running too long that
> > exhausts my desktop, how I can prevent it from happening? I am thinking of
> > setting a limit, which I can tolerate a 4 minutes window but not longer than
> > that.
> >
> > If this helps: On the properties of "Use query governor to prevent queries
> > exceeding specified cost", I need to set the cost, but don't know how much.
> >
> > Thanks.|||Hi
If you want to limit the query to 4 minutes, (4x60 = 240), so put 240 in the
setting box.
Instead of aborting the query, rather look at why it is not performaing well.
Look at http://www.sql-server-performance.com
Regards
Mike
"C TO" wrote:
> Dear Mike,
> Thanks but sorry for my confusing question. I still don't know what the BOL
> means by that. I do not know how to estimate the cost limitation I need to
> set.
> "Mike Epprecht (SQL MVP)" wrote:
> > Hi
> >
> > From BOL:
> >
> > query governor cost limit Option
> > Use the query governor cost limit option to specify an upper limit for the
> > time in which a query can run. Query cost refers to the estimated elapsed
> > time, in seconds, required to execute a query on a specific hardware
> > configuration.
> >
> > Regards
> > Mike
> >
> > "C TO" wrote:
> >
> > > To prevent a test (which can poorly written) query for running too long that
> > > exhausts my desktop, how I can prevent it from happening? I am thinking of
> > > setting a limit, which I can tolerate a 4 minutes window but not longer than
> > > that.
> > >
> > > If this helps: On the properties of "Use query governor to prevent queries
> > > exceeding specified cost", I need to set the cost, but don't know how much.
> > >
> > > Thanks.|||C TO wrote:
> To prevent a test (which can poorly written) query for running too
> long that exhausts my desktop, how I can prevent it from happening? I
> am thinking of setting a limit, which I can tolerate a 4 minutes
> window but not longer than that.
> If this helps: On the properties of "Use query governor to prevent
> queries exceeding specified cost", I need to set the cost, but don't
> know how much.
> Thanks.
You could also set a query timeout from Query Analyzer or your
application for 4,000ms which forces the command to abort if it's not
completed within the allotted time.
--
David Gugick
Imceda Software
www.imceda.com

How to estimate query governor cost setting?

To prevent a test (which can poorly written) query for running too long that
exhausts my desktop, how I can prevent it from happening? I am thinking of
setting a limit, which I can tolerate a 4 minutes window but not longer than
that.
If this helps: On the properties of "Use query governor to prevent queries
exceeding specified cost", I need to set the cost, but don't know how much.
Thanks.
Hi
From BOL:
query governor cost limit Option
Use the query governor cost limit option to specify an upper limit for the
time in which a query can run. Query cost refers to the estimated elapsed
time, in seconds, required to execute a query on a specific hardware
configuration.
Regards
Mike
"C TO" wrote:

> To prevent a test (which can poorly written) query for running too long that
> exhausts my desktop, how I can prevent it from happening? I am thinking of
> setting a limit, which I can tolerate a 4 minutes window but not longer than
> that.
> If this helps: On the properties of "Use query governor to prevent queries
> exceeding specified cost", I need to set the cost, but don't know how much.
> Thanks.
|||Dear Mike,
Thanks but sorry for my confusing question. I still don't know what the BOL
means by that. I do not know how to estimate the cost limitation I need to
set.
"Mike Epprecht (SQL MVP)" wrote:
[vbcol=seagreen]
> Hi
> From BOL:
> query governor cost limit Option
> Use the query governor cost limit option to specify an upper limit for the
> time in which a query can run. Query cost refers to the estimated elapsed
> time, in seconds, required to execute a query on a specific hardware
> configuration.
> Regards
> Mike
> "C TO" wrote:
|||Hi
If you want to limit the query to 4 minutes, (4x60 = 240), so put 240 in the
setting box.
Instead of aborting the query, rather look at why it is not performaing well.
Look at http://www.sql-server-performance.com
Regards
Mike
"C TO" wrote:
[vbcol=seagreen]
> Dear Mike,
> Thanks but sorry for my confusing question. I still don't know what the BOL
> means by that. I do not know how to estimate the cost limitation I need to
> set.
> "Mike Epprecht (SQL MVP)" wrote:
|||C TO wrote:
> To prevent a test (which can poorly written) query for running too
> long that exhausts my desktop, how I can prevent it from happening? I
> am thinking of setting a limit, which I can tolerate a 4 minutes
> window but not longer than that.
> If this helps: On the properties of "Use query governor to prevent
> queries exceeding specified cost", I need to set the cost, but don't
> know how much.
> Thanks.
You could also set a query timeout from Query Analyzer or your
application for 4,000ms which forces the command to abort if it's not
completed within the allotted time.
David Gugick
Imceda Software
www.imceda.com

How to enter this command line sql statement...??

:confused: I am trying to use a program called ODBCVIEW to query a database from the command line, and write it to text file. The instructions look easy, But I am illiterate to translating command line syntax.
I am not sure if I use the ">" , "[", etc... or if I leave them out. Can some one show me exactly how the finished code is supposed to look (in laymans)...

The program I am using to query the DB is called ODBCVIEW. Here is a link to the page with the syntax(located at the bottom) - http://www.slik.co.nz/HTML_help/odbc_view.htm

...and I have also pasted it below:

-COPIED FROM WEBSITE:
ODBCView also supports a non-interactive command line mode to execute a query and save the results to a text file. The syntax is as follows:

ODBCView.exe <DSN=DataSourceName;UID=User;PWD=Password> [<SQLScript.sql>] [<OutputFile.htm|csv|txt>]

Where:

DataSource
The desired datasource name.

UID
An optional user name to logon to the database

PWD
An optional user password

SQLScript
The query to execute.

OutputFile
The path to the output file. The files extension determines the format. Use htm or html to HTML, csv for CSV.If you are only trying to query a database and write the results to a file, better try WinSQL (http://www.download.com/3001-10255_4-10213451.html). ;)|||:D Just what I was looking for!

I'm installing it now - Does it have a 'command-line' mode?

How to enter a date parameter in Debugger

(This is prob. a really dumb question but it's driving me mad!!...)

I am using the Debugger in SQL Query Analyzer & want to set the value of a datetime parameter prior to executing the stored proc. The "Debug procedure" window allows me to specify the parameter values - but I can't get it to accept a datetime. The language is us_english & I've tried most ways if specifying the date - 01/02/2004, with/out quotes, 02 Jan 2004, as a full datetime, swapping day/month values etc etc. The procedure always fails immediately with: Invalid character value for cast specification.

Thanks.Got it ... finally!

yyyy-mm-dd

Argggggh.

How to enforce SQL Server 2005 to use Worktable?

I have a problem in SQL Server 2005. In some cases SQL Server produces an execution plan of complex query (8 joins of views, some of views contains couple of joins) which does not contain a woktable creation in tempdb. As a result time of query execution increasion for about 5 seconds to about 4 minutes. All necessary indexes are created. It sims all data located in cache. Is there any way to enforce SQL Server to create worktable?

Query

SELECT [a0].[id],[a0].[Priority],[a0].[Heading],[a0].[DocumentDate],[a0].[LastName],[a0].[FirstName],[a2].[Name],[a1].[Position],[a4].[ContactTime],[a4].[Subject],[a0].[WorkPhone],[a0].[MobilePhone],[a0].[FaxNumber],[a0].[PrimaryEmail],[a5].[ContactTime],[a6].[Value],[a7].[id],[a7].[id_class],[a8].[id],[a8].[id_class],[a0].[FIO]
FROM [Bkc_EBM_Person_View] [a0]
LEFT JOIN [Bkc_EBM_ContactsInfo_View] [a3] ON ( a0.ContactsInfo_id = a3.[id] )
LEFT JOIN [Bkc_EBM_Contact_View] [a4] ON ( a3.LastContact_id = a4.[id] )
LEFT JOIN [Bkc_EBM_Contact_View] [a5] ON ( a3.NextContact_id = a5.[id] )
LEFT JOIN [Bkc_EBM_PersonType_View] [a6] ON ( a0.PersonType_id = a6.[id] )
LEFT JOIN [Bkc_EBM_Employment_View] [a1] ON ( a0.PrimaryEmployment_id = a1.[id] )
LEFT JOIN [Bkc_EBM_Client_View] [a2] ON ( a1.Client_id = a2.[id] )
LEFT JOIN [Bkc_EBM_Person_View] [a7] ON ( a0.Responsible_id = a7.[id] )
LEFT JOIN [Bkc_EBM_Department_View] [a8] ON ( a0.Department_id = a8.[id] )

Statistics

(2454 row(s) affected)

Table 'ReadRights'. Scan count 2455, logical reads 109411, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

Table 'ProcessAccounts'. Scan count 11102, logical reads 22266, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

Table 'Bkc_EBM_Department'. Scan count 0, logical reads 4908, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

Table 'Bkc_EBM_Person'. Scan count 0, logical reads 38986, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

Table 'Bkc_EBM_Client'. Scan count 0, logical reads 4826, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

Table 'Bkc_EBM_Employment'. Scan count 0, logical reads 83632238, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

Table 'Bkc_EBM_PersonType'. Scan count 0, logical reads 4908, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

Table 'Bkc_EBM_Contact'. Scan count 0, logical reads 9816, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

Table 'Bkc_EBM_ContactsInfo'. Scan count 0, logical reads 4908, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

(1 row(s) affected)

SQL Server Execution Times:

CPU time = 231719 ms,elapsed time = 253491 ms.

Execution plan

http://rsdn.ru/File/22090/plan1.rar

Please post the view definitions.

It looks like your view definition for BKc_EBM_Employment has a bad join in it, You are processing 640Gb of data from the BKcEBM_Employment table

|||try forcing a recompile.

e.g.
select *
from ...
option (recompile)|||

Below is the view definition

Bkc_EBM_Employment is a table which connects Bkc_EBM_Person and Bkc_EBM_Client in a many-to-many relation.

ReadRights is a table which defines rights of user account to view particular document in system

processaccounts is a table, to which Application server writes corrspondence between current spid and user account id, before executing a query

USE [Oblik_CRM]

GO

/****** Object: View [dbo].[Bkc_EBM_Employment_View] Script Date: 10/04/2006 10:18:38 ******/

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

CREATE VIEW [dbo].[Bkc_EBM_Employment_View] WITH SCHEMABINDING AS

(SELECT [id], 1370 AS [id_class], cast([id] as varchar(64))+'_1370' AS [id_record], t.[EmployedPerson_id], t.[EmployedPerson_class_id], t.[Client_id], t.[Client_class_id], t.[Department_id], t.[Department_class_id], t.[Position], t.[PlaceOfWorkType_id], t.[PlaceOfWorkType_class_id], t.[RoleEmployee_id], t.[RoleEmployee_class_id], t.[FRC_id], t.[FRC_class_id], t.[InnerPhone], t.[IsPrimary], t.[IsFired], t.[EmploymentDate], t.[FiredDate], t.[FiredReason_id], t.[FiredReason_class_id], t.[Description], t.[RightToSign], t.[Heading], t.[Version] FROM dbo.Bkc_EBM_Employment t

inner join dbo.ReadRights r on (t.EmployedPerson_id = r.object_id) inner join dbo.ProcessAccounts pa WITH (NOLOCK) on (r.account_id = pa.account_id) where pa.spid=@.@.spid

)

|||

I rewrite the query without using viws. It helps a little because in new query data, that not needed by this query not queried by the views. But time of query execution is still to long. About 2 minutes

declare @.userID int

set @.userID = 104356

declare @.qp_0 int

set @.qp_0 = 0

DELETE ProcessAccounts WITH (ROWLOCK) WHERE spid=@.@.spid INSERT ProcessAccounts WITH (ROWLOCK) (account_id, spid) VALUES (@.userID, @.@.spid)

SELECT

[a0].[id],[a0].[Heading],[a0].[DocumentDate],[a0].[DocumentId],[a0].[Name],[a0].[PrimaryPhone],[a0].[PrimaryEmail],

[a1].[FIO],

[a3].[ContactTime],

[a4].[WorkPhone],[a4].[WorkEmail],[a4].[FIO],

[a5].[Value],

[a6].[Position],

[a7].[ContactTime]

FROM

(

SELECT [a0].[id],[a0].[Heading],[a0].[DocumentDate],[a0].[DocumentId],[a0].[Name],[a0].[PrimaryPhone],[a0].[PrimaryEmail], a0.Responsible_id, a0.ClientType_id, a0.ContactsInfo_id, a0.IsTemplate FROM [Bkc_EBM_Client] [a0]

INNER JOIN [ReadRights] [a0r] ON ([a0].[id] = [a0r].[object_id] )

INNER JOIN ( SELECT [account_id] FROM [ProcessAccounts] WITH (NOLOCK) WHERE [spid] = @.@.SPID ) [a0pa] ON ( [a0r].[account_id] = [a0pa].[account_id] )

) [a0]

LEFT JOIN [Bkc_EBM_ClientType] [a5] ON ( a0.ClientType_id = a5.[id] )

LEFT JOIN

(

SELECT [a1].[id], [a1].[FIO] FROM [Bkc_EBM_Person] [a1]

INNER JOIN [ReadRights] [a1r] ON ([a1].[id] = [a1r].[object_id] )

INNER JOIN ( SELECT [account_id] FROM [ProcessAccounts] WITH (NOLOCK) WHERE [spid] = @.@.SPID ) [a1pa] ON ( [a1r].[account_id] = [a1pa].[account_id] )

) [a1] ON ( a0.Responsible_id = a1.[id] )

LEFT JOIN [Bkc_EBM_ContactsInfo] [a2] ON ( a0.ContactsInfo_id = a2.[id] )

LEFT JOIN

(

SELECT [a3].[id], [a3].[ContactTime] FROM [Bkc_EBM_Contact] [a3]

INNER JOIN [ReadRights] [a3r] ON ([a3].[id] = [a3r].[object_id] )

INNER JOIN ( SELECT [account_id] FROM [ProcessAccounts] WITH (NOLOCK) WHERE [spid] = @.@.SPID ) [a3pa] ON ( [a3r].[account_id] = [a3pa].[account_id] )

) [a3] ON ( a2.LastContact_id = a3.[id] )

LEFT JOIN

(

SELECT [a4].[id], [a4].[WorkPhone],[a4].[WorkEmail],[a4].[FIO], [a4].[PrimaryEmployment_id] FROM [Bkc_EBM_Person] [a4]

INNER JOIN [ReadRights] [a4r] ON ([a4].[id] = [a4r].[object_id] )

INNER JOIN ( SELECT [account_id] FROM [ProcessAccounts] WITH (NOLOCK) WHERE [spid] = @.@.SPID ) [a4pa] ON ( [a4r].[account_id] = [a4pa].[account_id] )

) [a4] ON ( a2.LastContactPerson_id = a4.[id] )

LEFT JOIN

(

SELECT [a6].[id], [a6].[Position] FROM [Bkc_EBM_Employment] [a6]

INNER JOIN [ReadRights] [a6r] ON ([a6].[EmployedPerson_id] = [a6r].[object_id] )

INNER JOIN ( SELECT [account_id] FROM [ProcessAccounts] WITH (NOLOCK) WHERE [spid] = @.@.SPID ) [a6pa] ON ( [a6r].[account_id] = [a6pa].[account_id] )

) [a6] ON ( a4.PrimaryEmployment_id = a6.[id] )

LEFT JOIN

(

SELECT [a7].[id], [a7].[ContactTime] FROM [Bkc_EBM_Contact] [a7]

INNER JOIN [ReadRights] [a7r] ON ([a7].[id] = [a7r].[object_id] )

INNER JOIN ( SELECT [account_id] FROM [ProcessAccounts] WITH (NOLOCK) WHERE [spid] = @.@.SPID ) [a7pa] ON ( [a7r].[account_id] = [a7pa].[account_id] )

) [a7] ON ( a2.NextContact_id = a7.[id] )

WHERE ([a0].[IsTemplate] = @.qp_0 OR [a0].[IsTemplate] IS NULL )

DELETE ProcessAccounts WITH (ROWLOCK) WHERE spid=@.@.spid

Statistics

(1750 row(s) affected)

Table 'ReadRights'. Scan count 5891, logical reads 222578, physical reads 425, read-ahead reads 283, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

Table 'ProcessAccounts'. Scan count 6, logical reads 5891, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

Table 'Bkc_EBM_Contact'. Scan count 0, logical reads 7000, physical reads 98, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

Table 'Bkc_EBM_Employment'. Scan count 0, logical reads 33686288, physical reads 33, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

Table 'Bkc_EBM_Person'. Scan count 0, logical reads 7000, physical reads 60, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

Table 'Bkc_EBM_ContactsInfo_View'. Scan count 0, logical reads 3500, physical reads 5, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

Table 'Bkc_EBM_ClientType_View'. Scan count 0, logical reads 3500, physical reads 1, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

Table 'Bkc_EBM_Client'. Scan count 0, logical reads 33252, physical reads 43, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

(1 row(s) affected)

SQL Server Execution Times:

CPU time = 111797 ms, elapsed time = 123889 ms.

Execution Plan

http://rsdn.ru/File/22090/plan4.rar

|||

Please post the scripts for all the tables involved and indexes.

To get performance you need to reduce the amount of data being read from Bkc_EBM_Employment

|||Do you have a where clause on your query ?|||

SimonS_ wrote:

Do you have a where clause on your query ?

Yes "WHERE ([a0].[IsTemplate] = @.qp_0 OR [a0].[IsTemplate] IS NULL ) " (see query in the answer above) but there is no records in database filtered by this condition.

About database

'ReadRights' ~ 500000 records
'ProcessAccounts' 1 record
'Bkc_EBM_Person' ~ 2500 records
'Bkc_EBM_Client' ~ 1700 records
'Bkc_EBM_ClientType' ~ 20 records
'Bkc_EBM_ContactsInfo' ~ 4000 records
'Bkc_EBM_Contact' ~ 5000 records
'Bkc_EBM_Employment' ~ 2500 records

Very strange, but it sims RECOMPILE option helps. Worktable is created even right after SQL Server restart. If RECOMPLIE not used after server restart Worktable not created.

|||

The problem is query plans. Your query won't change from one user to the next or from one template to the next however this means the same query plan will be used. However the same query plan will not be optimal for all situations.

What can happen is that a plan is put in the cache based on the first set of parameters supplied, if this plan is not suitable for all queries you can end up with the problem above.

The recompile will address this at the expense of having to compile the query every time.

|||

Thank you for your help Simon. RECOMPILE is really helps.

Maybe in my case using of parameters in a query is not the best choise? Especially @.userID ?

|||Can you still post the CREATE table statements and CREATE View statements so I can understand your query better, its quite difficult with your use of views to understand what is joining to what.|||

Script will be quite large. Maybe by email?

|||try SQLForumsATonarcDOTcom|||I send the script. Please check.|||Another problem. In SQL Server 2000 option (recompile) is not supported. Is there any way to enforce SQL Server 2000 to recompile execution plan every time?

How to enforce SQL Server 2005 to use Worktable?

I have a problem in SQL Server 2005. In some cases SQL Server produces an execution plan of complex query (8 joins of views, some of views contains couple of joins) which does not contain a woktable creation in tempdb. As a result time of query execution increasion for about 5 seconds to about 4 minutes. All necessary indexes are created. It sims all data located in cache. Is there any way to enforce SQL Server to create worktable?

Query

SELECT [a0].[id],[a0].[Priority],[a0].[Heading],[a0].[DocumentDate],[a0].[LastName],[a0].[FirstName],[a2].[Name],[a1].[Position],[a4].[ContactTime],[a4].[Subject],[a0].[WorkPhone],[a0].[MobilePhone],[a0].[FaxNumber],[a0].[PrimaryEmail],[a5].[ContactTime],[a6].[Value],[a7].[id],[a7].[id_class],[a8].[id],[a8].[id_class],[a0].[FIO]
FROM [Bkc_EBM_Person_View] [a0]
LEFT JOIN [Bkc_EBM_ContactsInfo_View] [a3] ON ( a0.ContactsInfo_id = a3.[id] )
LEFT JOIN [Bkc_EBM_Contact_View] [a4] ON ( a3.LastContact_id = a4.[id] )
LEFT JOIN [Bkc_EBM_Contact_View] [a5] ON ( a3.NextContact_id = a5.[id] )
LEFT JOIN [Bkc_EBM_PersonType_View] [a6] ON ( a0.PersonType_id = a6.[id] )
LEFT JOIN [Bkc_EBM_Employment_View] [a1] ON ( a0.PrimaryEmployment_id = a1.[id] )
LEFT JOIN [Bkc_EBM_Client_View] [a2] ON ( a1.Client_id = a2.[id] )
LEFT JOIN [Bkc_EBM_Person_View] [a7] ON ( a0.Responsible_id = a7.[id] )
LEFT JOIN [Bkc_EBM_Department_View] [a8] ON ( a0.Department_id = a8.[id] )

Statistics

(2454 row(s) affected)

Table 'ReadRights'. Scan count 2455, logical reads 109411, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

Table 'ProcessAccounts'. Scan count 11102, logical reads 22266, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

Table 'Bkc_EBM_Department'. Scan count 0, logical reads 4908, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

Table 'Bkc_EBM_Person'. Scan count 0, logical reads 38986, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

Table 'Bkc_EBM_Client'. Scan count 0, logical reads 4826, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

Table 'Bkc_EBM_Employment'. Scan count 0, logical reads 83632238, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

Table 'Bkc_EBM_PersonType'. Scan count 0, logical reads 4908, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

Table 'Bkc_EBM_Contact'. Scan count 0, logical reads 9816, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

Table 'Bkc_EBM_ContactsInfo'. Scan count 0, logical reads 4908, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

(1 row(s) affected)

SQL Server Execution Times:

CPU time = 231719 ms,elapsed time = 253491 ms.

Execution plan

http://rsdn.ru/File/22090/plan1.rar

Please post the view definitions.

It looks like your view definition for BKc_EBM_Employment has a bad join in it, You are processing 640Gb of data from the BKcEBM_Employment table

|||try forcing a recompile.

e.g.
select *
from ...
option (recompile)|||

Below is the view definition

Bkc_EBM_Employment is a table which connects Bkc_EBM_Person and Bkc_EBM_Client in a many-to-many relation.

ReadRights is a table which defines rights of user account to view particular document in system

processaccounts is a table, to which Application server writes corrspondence between current spid and user account id, before executing a query

USE [Oblik_CRM]

GO

/****** Object: View [dbo].[Bkc_EBM_Employment_View] Script Date: 10/04/2006 10:18:38 ******/

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

CREATE VIEW [dbo].[Bkc_EBM_Employment_View] WITH SCHEMABINDING AS

(SELECT [id], 1370 AS [id_class], cast([id] as varchar(64))+'_1370' AS [id_record], t.[EmployedPerson_id], t.[EmployedPerson_class_id], t.[Client_id], t.[Client_class_id], t.[Department_id], t.[Department_class_id], t.[Position], t.[PlaceOfWorkType_id], t.[PlaceOfWorkType_class_id], t.[RoleEmployee_id], t.[RoleEmployee_class_id], t.[FRC_id], t.[FRC_class_id], t.[InnerPhone], t.[IsPrimary], t.[IsFired], t.[EmploymentDate], t.[FiredDate], t.[FiredReason_id], t.[FiredReason_class_id], t.[Description], t.[RightToSign], t.[Heading], t.[Version] FROM dbo.Bkc_EBM_Employment t

inner join dbo.ReadRights r on (t.EmployedPerson_id = r.object_id) inner join dbo.ProcessAccounts pa WITH (NOLOCK) on (r.account_id = pa.account_id) where pa.spid=@.@.spid

)

|||

I rewrite the query without using viws. It helps a little because in new query data, that not needed by this query not queried by the views. But time of query execution is still to long. About 2 minutes

declare @.userID int

set @.userID = 104356

declare @.qp_0 int

set @.qp_0 = 0

DELETE ProcessAccounts WITH (ROWLOCK) WHERE spid=@.@.spid INSERT ProcessAccounts WITH (ROWLOCK) (account_id, spid) VALUES (@.userID, @.@.spid)

SELECT

[a0].[id],[a0].[Heading],[a0].[DocumentDate],[a0].[DocumentId],[a0].[Name],[a0].[PrimaryPhone],[a0].[PrimaryEmail],

[a1].[FIO],

[a3].[ContactTime],

[a4].[WorkPhone],[a4].[WorkEmail],[a4].[FIO],

[a5].[Value],

[a6].[Position],

[a7].[ContactTime]

FROM

(

SELECT [a0].[id],[a0].[Heading],[a0].[DocumentDate],[a0].[DocumentId],[a0].[Name],[a0].[PrimaryPhone],[a0].[PrimaryEmail], a0.Responsible_id, a0.ClientType_id, a0.ContactsInfo_id, a0.IsTemplate FROM [Bkc_EBM_Client] [a0]

INNER JOIN [ReadRights] [a0r] ON ([a0].[id] = [a0r].[object_id] )

INNER JOIN ( SELECT [account_id] FROM [ProcessAccounts] WITH (NOLOCK) WHERE [spid] = @.@.SPID ) [a0pa] ON ( [a0r].[account_id] = [a0pa].[account_id] )

) [a0]

LEFT JOIN [Bkc_EBM_ClientType] [a5] ON ( a0.ClientType_id = a5.[id] )

LEFT JOIN

(

SELECT [a1].[id], [a1].[FIO] FROM [Bkc_EBM_Person] [a1]

INNER JOIN [ReadRights] [a1r] ON ([a1].[id] = [a1r].[object_id] )

INNER JOIN ( SELECT [account_id] FROM [ProcessAccounts] WITH (NOLOCK) WHERE [spid] = @.@.SPID ) [a1pa] ON ( [a1r].[account_id] = [a1pa].[account_id] )

) [a1] ON ( a0.Responsible_id = a1.[id] )

LEFT JOIN [Bkc_EBM_ContactsInfo] [a2] ON ( a0.ContactsInfo_id = a2.[id] )

LEFT JOIN

(

SELECT [a3].[id], [a3].[ContactTime] FROM [Bkc_EBM_Contact] [a3]

INNER JOIN [ReadRights] [a3r] ON ([a3].[id] = [a3r].[object_id] )

INNER JOIN ( SELECT [account_id] FROM [ProcessAccounts] WITH (NOLOCK) WHERE [spid] = @.@.SPID ) [a3pa] ON ( [a3r].[account_id] = [a3pa].[account_id] )

) [a3] ON ( a2.LastContact_id = a3.[id] )

LEFT JOIN

(

SELECT [a4].[id], [a4].[WorkPhone],[a4].[WorkEmail],[a4].[FIO], [a4].[PrimaryEmployment_id] FROM [Bkc_EBM_Person] [a4]

INNER JOIN [ReadRights] [a4r] ON ([a4].[id] = [a4r].[object_id] )

INNER JOIN ( SELECT [account_id] FROM [ProcessAccounts] WITH (NOLOCK) WHERE [spid] = @.@.SPID ) [a4pa] ON ( [a4r].[account_id] = [a4pa].[account_id] )

) [a4] ON ( a2.LastContactPerson_id = a4.[id] )

LEFT JOIN

(

SELECT [a6].[id], [a6].[Position] FROM [Bkc_EBM_Employment] [a6]

INNER JOIN [ReadRights] [a6r] ON ([a6].[EmployedPerson_id] = [a6r].[object_id] )

INNER JOIN ( SELECT [account_id] FROM [ProcessAccounts] WITH (NOLOCK) WHERE [spid] = @.@.SPID ) [a6pa] ON ( [a6r].[account_id] = [a6pa].[account_id] )

) [a6] ON ( a4.PrimaryEmployment_id = a6.[id] )

LEFT JOIN

(

SELECT [a7].[id], [a7].[ContactTime] FROM [Bkc_EBM_Contact] [a7]

INNER JOIN [ReadRights] [a7r] ON ([a7].[id] = [a7r].[object_id] )

INNER JOIN ( SELECT [account_id] FROM [ProcessAccounts] WITH (NOLOCK) WHERE [spid] = @.@.SPID ) [a7pa] ON ( [a7r].[account_id] = [a7pa].[account_id] )

) [a7] ON ( a2.NextContact_id = a7.[id] )

WHERE ([a0].[IsTemplate] = @.qp_0 OR [a0].[IsTemplate] IS NULL )

DELETE ProcessAccounts WITH (ROWLOCK) WHERE spid=@.@.spid

Statistics

(1750 row(s) affected)

Table 'ReadRights'. Scan count 5891, logical reads 222578, physical reads 425, read-ahead reads 283, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

Table 'ProcessAccounts'. Scan count 6, logical reads 5891, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

Table 'Bkc_EBM_Contact'. Scan count 0, logical reads 7000, physical reads 98, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

Table 'Bkc_EBM_Employment'. Scan count 0, logical reads 33686288, physical reads 33, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

Table 'Bkc_EBM_Person'. Scan count 0, logical reads 7000, physical reads 60, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

Table 'Bkc_EBM_ContactsInfo_View'. Scan count 0, logical reads 3500, physical reads 5, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

Table 'Bkc_EBM_ClientType_View'. Scan count 0, logical reads 3500, physical reads 1, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

Table 'Bkc_EBM_Client'. Scan count 0, logical reads 33252, physical reads 43, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

(1 row(s) affected)

SQL Server Execution Times:

CPU time = 111797 ms, elapsed time = 123889 ms.

Execution Plan

http://rsdn.ru/File/22090/plan4.rar

|||

Please post the scripts for all the tables involved and indexes.

To get performance you need to reduce the amount of data being read from Bkc_EBM_Employment

|||Do you have a where clause on your query ?|||

SimonS_ wrote:

Do you have a where clause on your query ?

Yes "WHERE ([a0].[IsTemplate] = @.qp_0 OR [a0].[IsTemplate] IS NULL ) " (see query in the answer above) but there is no records in database filtered by this condition.

About database

'ReadRights' ~ 500000 records
'ProcessAccounts' 1 record
'Bkc_EBM_Person' ~ 2500 records
'Bkc_EBM_Client' ~ 1700 records
'Bkc_EBM_ClientType' ~ 20 records
'Bkc_EBM_ContactsInfo' ~ 4000 records
'Bkc_EBM_Contact' ~ 5000 records
'Bkc_EBM_Employment' ~ 2500 records

Very strange, but it sims RECOMPILE option helps. Worktable is created even right after SQL Server restart. If RECOMPLIE not used after server restart Worktable not created.

|||

The problem is query plans. Your query won't change from one user to the next or from one template to the next however this means the same query plan will be used. However the same query plan will not be optimal for all situations.

What can happen is that a plan is put in the cache based on the first set of parameters supplied, if this plan is not suitable for all queries you can end up with the problem above.

The recompile will address this at the expense of having to compile the query every time.

|||

Thank you for your help Simon. RECOMPILE is really helps.

Maybe in my case using of parameters in a query is not the best choise? Especially @.userID ?

|||Can you still post the CREATE table statements and CREATE View statements so I can understand your query better, its quite difficult with your use of views to understand what is joining to what.|||

Script will be quite large. Maybe by email?

|||try SQLForumsATonarcDOTcom|||I send the script. Please check.|||Another problem. In SQL Server 2000 option (recompile) is not supported. Is there any way to enforce SQL Server 2000 to recompile execution plan every time?

Monday, March 26, 2012

How to encorporate IF

How can I put an If statement saying If # RECORDS returned from the query below
IF # records returned is > 1 then
SUM(rmstranamt) AS rmstranamt10
ELSE
rmstranamt AS rmstranamt10

here's my statement

-


SELECT RMSFILENUM,
rmstranamt AS rmstranamt10 <--If statement goes here base on if the amount of records found in select is >1 or not
FROM RFINANL
WHERE RMSTRANCDE = '10'
GROUP BY RMSFILENUM, rmstranamt
) AS rf10 ON rf10.RMSFILENUM = rm.RMSFILENUM

I want to return sum(rmstranamt) AS rmstranamt10 in cases where the same query produces > 1 records
In other words if this:
SELECT RMSFILENUM,
rmstranamt AS rmstranamt10
FROM RFINANL
WHERE RMSTRANCDE = '10'
GROUP BY RMSFILENUM, rmstranamt
produces > 1 records, then I don't want to return rmstranamt AS rmstranamt10, I want to return sum(rmstranamt) AS rmstranamt10

Wouldn't

SUM(rmstranamt)
be the same as
rmstranamt

in the case of one record? Think you should just include the sum and not worry about it.

- Brad
|||

you would think....I've spent 3 days on this...check it out more here:

http://www.experts-exchange.com/Databases/Microsoft_SQL_Server/Q_21692997.html

|||I see your issue now, but the problem isn't the SUM function rather the GROUP BY clause.

Just remmove the rmstranamt from your GROUP BY to achieve the desired results, otherwise each row returned represents a SUM applied to a GROUP that has one row.

- Brad|||Brad, you mean remove rmstranamt from my last Group By right? If I do that then It errors out saying that rmstranamt needs to be in it...so what do I do?|||Brad, ok yes, that works but to a certain point. My main problem is when I plug in an account that I know has more than 1 results from my first INNER JOIN query, it throws off my end aggregation and I end up with 2 account rows rather than one for that account|||SELECT RMSFILENUM, sum(rmstranamt) rmstranamt10
FROM RFINANL
WHERE RMSTRANCDE = '10'
GROUP BY RMSFILENUM|||

Hi,

SELECT RMSFILENUM
into #tmp

FROM RFINANL
WHERE RMSTRANCDE = '10'
GROUP BY RMSFILENUM having count(rmstranamt) <= 1

SELECT RMSFILENUM,
sum(rmstranamt )AS rmstranamt10

FROM RFINANL
WHERE RMSTRANCDE = '10'
GROUP BY RMSFILENUM having count(rmstranamt) > 1

union

SELECT r.RMSFILENUM,
rmstranamt AS rmstranamt10

FROM RFINANL r inner join #tmp t on r.RMSFILENUM = t.RMSFILENUM
GROUP BY r.RMSFILENUM, r.rmstranamt

Regards

How to encorporate IF

How can I put an If statement saying If # RECORDS returned from the query below
IF # records returned is > 1 then
SUM(rmstranamt) AS rmstranamt10
ELSE
rmstranamt AS rmstranamt10

here's my statement

-


SELECT RMSFILENUM,
rmstranamt AS rmstranamt10 <--If statement goes here base on if the amount of records found in select is >1 or not
FROM RFINANL
WHERE RMSTRANCDE = '10'
GROUP BY RMSFILENUM, rmstranamt
) AS rf10 ON rf10.RMSFILENUM = rm.RMSFILENUM

I want to return sum(rmstranamt) AS rmstranamt10 in cases where the same query produces > 1 records
In other words if this:
SELECT RMSFILENUM,
rmstranamt AS rmstranamt10
FROM RFINANL
WHERE RMSTRANCDE = '10'
GROUP BY RMSFILENUM, rmstranamt
produces > 1 records, then I don't want to return rmstranamt AS rmstranamt10, I want to return sum(rmstranamt) AS rmstranamt10

Wouldn't

SUM(rmstranamt)
be the same as
rmstranamt

in the case of one record? Think you should just include the sum and not worry about it.

- Brad
|||

you would think....I've spent 3 days on this...check it out more here:

http://www.experts-exchange.com/Databases/Microsoft_SQL_Server/Q_21692997.html

|||I see your issue now, but the problem isn't the SUM function rather the GROUP BY clause.

Just remmove the rmstranamt from your GROUP BY to achieve the desired results, otherwise each row returned represents a SUM applied to a GROUP that has one row.

- Brad|||Brad, you mean remove rmstranamt from my last Group By right? If I do that then It errors out saying that rmstranamt needs to be in it...so what do I do?|||Brad, ok yes, that works but to a certain point. My main problem is when I plug in an account that I know has more than 1 results from my first INNER JOIN query, it throws off my end aggregation and I end up with 2 account rows rather than one for that account|||SELECT RMSFILENUM, sum(rmstranamt) rmstranamt10
FROM RFINANL
WHERE RMSTRANCDE = '10'
GROUP BY RMSFILENUM|||

Hi,

SELECT RMSFILENUM
into #tmp

FROM RFINANL
WHERE RMSTRANCDE = '10'
GROUP BY RMSFILENUM having count(rmstranamt) <= 1

SELECT RMSFILENUM,
sum(rmstranamt )AS rmstranamt10

FROM RFINANL
WHERE RMSTRANCDE = '10'
GROUP BY RMSFILENUM having count(rmstranamt) > 1

union

SELECT r.RMSFILENUM,
rmstranamt AS rmstranamt10

FROM RFINANL r inner join #tmp t on r.RMSFILENUM = t.RMSFILENUM
GROUP BY r.RMSFILENUM, r.rmstranamt

Regards

Wednesday, March 21, 2012

How to enable Ah Hoc Query in SQL 2000

Hi guys

I have a program which imports data into sql server from csv files. This program uses the something like this

CREATE PROCEDURE MyImport

(

@.FileName AS VARCHAR(200)

)

AS

SET NOCOUNT ON

DECLARE @.SQL VARCHAR(4000)

SET @.SQL = ' SELECT *

FROM OpenRowset(''MSDASQL'', ''Driver={Microsoft Text Driver (*.txt; *.csv)}; DefaultDir=C:\;'', ''SELECT * FROM ' + QUOTENAME(@.FileName) + '' + ''') as t

'

EXEC (@.SQL)

when i excute this i get a permission error saying the account i specified in the web config doesn't have rights to run these type of scripts. I tried using the sa account which works. But its not recommended to setup applications to access the database using the sa account.

i did some research and i found out that yon can actually enable that by change a registry key. But i cant find the MSDASQL datasource under ms sql server providers in the registry.

Any other ways i can enable this?

Have a look at http://www.asp101.com/articles/john/connstring/default.asp|||

Excellent article. Will give it a go at it on monday.

Thanks

|||

Hi TATWORTH

The link you provided was good but not what im looking for. If you read my post carefully you will know. I have a stored procedure which will select from a file passed in as a parameter using theMSDASQL provider. NOW THIS IS ALL DONE IN SQL not in my app.

I was saying that the account i specified in the web.config does not have permissions to use the MSDASQL provider inside of SQL. The account i used only have rights to run stored procedures and that is it. But my script is written inside of a stored procedure. The reason for not being able to run the script inside of the procedure is because this procedure produces a dynamic script and executes that inside of the stored procedure.

i heard you can enable a registry key which will enable the use of that provider, but i cant find theMSDASQLprovider in the registry.

i was looking for a way to grant permissions to (web_user account) execute these type of queries.

Hope this cleared things up

Cheers

How to eliminate the commas from the end in sql query when the column value is null

HI

I have three different columns as email1,email2 , email3.I am concatinating these columns into one i.e EMail like

select ISNULL(dbo.tblperson.Email1, N'') +';'+ISNULL(dbo.tblperson.Email2, N'') +';'+ISNULL(dbo.tblperson.Email3, N'')ASEmail from tablename.

One eg of the output of the above query when email2,email3 are having null values in the table is :

jacky_foo@.mfa.gov.sg;;

means it is inserting semicoluns whenever there is a null value in the particular column. I want to remove this extra semicolumn whenever there is null value in the column.

Please let me know how can i do this

If you just change SQL a bit you have the answer, see below

select ISNULL(dbo.tblperson.Email1+ ';', N'') + ISNULL(dbo.tblperson.Email2 + ';', N'') + ISNULL(dbo.tblperson.Email3 + ';', N'')ASEmail from tablename.

|||

I tried this it worked a bit but not completely.Now I am getting the semicolumn at the end if there is null for the third column or you can say for the last column.

|||

There is probably a quick easy way to do it, but this will work:

select ISNULL(dbo.tblperson.Email1, N'') + ISNULL(CASE WHEN dbo.tblperson.Email1 IS NOT NULL THEN ';' ELSE '' END+dbo.tblperson.Email2, N'') + ISNULL(CASE WHEN dbo.tblperson.Email1 IS NOT NULL OR dbo.tblperson.Email2 IS NOT NULL THEN ';' ELSE '' END+dbo.tblperson.Email3, N'')ASEmail from tablename.

|||

Another way is to first normalize your data:

SELECT Email1 As Email FROM dbo.tblPerson
UNION ALL
SELECT Email2 As Email FROM dbo.tblPerson
UNION ALL
SELECT Email3 As Email FROM dbo.tblPerson

Now use the normalized data in a query like:

DECLARE @.Email varchar(max)

SELECT @.Email=ISNULL(@.Email+';','')+Email

FROM (

SELECT Email1 As Email FROM dbo.tblPerson
UNION ALL
SELECT Email2 As Email FROM dbo.tblPerson
UNION ALL
SELECT Email3 As Email FROM dbo.tblPerson

) t1

SELECT @.Email AS Email

|||

Another way is to use one of the many string concatenation techniques once your data has been normalized.

There is a CONCATENATE aggregation function that you can install that will do the trick. (Microsoft supplies one somewhere, google "T-SQL string concatenation aggregate").

There is another technique using the FOR XML/PATH to do the same thing, but it's also kind of messy.

|||

I appreciate your reply. This query worked for me.

How to eliminate Space entries...?

Hey,
I have some field values entries in my database.. that are spaces like ' '. i wanna eliminate them.
When i use IS NOT NULL in query it only eliminates the rows with NULL values so how could i modify the query to eliminate the rows with spaces in the field value..

Thx in advance..where COALESCE(somecolumn,' ')<>' '|||Thank you very much sir..|||SELECT * FROM Table1 WHERE Col1 > ' '|||WHERE NULLIF(somecolumn,' ') IS NOT NULL

Monday, March 19, 2012

How to edit a subquery in query designer

Hello!

Is it possible to edit a subquery in the diagram and grid pane,without using the texteditor in the SQL pane?

The way i do it now (hopefully not the best way):
1 Create a tmp dataset with sql statement for the subquery
2 Rightclick in the original dataset and "Add a new derived tables"
4 Paste the sql code from tmp query to the original dataset.

After linking the original query with many subquerys, it is difficult to change any off the subquerys!

Best Regards

Hello,

Currently, Query Designer does not support designing sub-queries via Diagram Pane or Criteria Pane. Our team has been working on enabling the design time support for sub-queries and we hope to include it in future versions of Visual Studio.

Thanks!