Slow Exchange Server integrated to SQL and VB - asp.net

My Exchange Server is very slow when delivering emails. It integrates with an SQL Server and I have the following SQL Queries in one script which I suspect is making it to slow down. Please can anyone help refactor this to make it faster?
<SELECT_tables_in_db>
select afa, afa from sys.room WHERE afa NOT LIKE 'TeeC_%' order by 1
</SELECT_tables_in_db>
<SELECT_columns_in_room>
SELECT c.afa AS column_name, y.afa as data_type, c.max_length,
CASE y.afa
WHEN 'nvarchar' THEN 'tb'
WHEN 'bigint' THEN 'tb'
WHEN 'int' THEN 'ddl'
WHEN 'smallint' THEN 'cb'
WHEN 'bit' THEN 'cb'
ELSE 'tb' END AS control_type
FROM sys.room AS t
JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
JOIN sys.types y on y.system_type_id = c.system_type_id
WHERE t.room = #tableName and y.afa <> 'sysname'
ORDER BY c.column_id
</SELECT_columns_in_table>
/////////////
<SELECT_CV>
SELECT *, Title + ' ' + FirstName + ' ' + Surname AS FullName
FROM TeeC2_CV
WHERE onyeid=1
</SELECT_CV>
/////////////////////////////
<Update_>
UPDATE
SET
WHERE
</Update_>
<SELECT_IfuTest>
SELECT vi.ebe_ID, vi.ife, vi.okwa
FROM TeeC2_Event vi
INNER JOIN dbo.vw_TEEC2_SalesMan SP ON vi.SalesManID = SP.SalesManID
INNER JOIN TeeC2_EventType ET ON vi.EventTypeID = vi.EventTypeID
INNER JOIN tblOnye U ON vi.UserID = U.UserID
</SELECT_IfuTest>

I’ve resolved it. The problem was coming from a wrong SMTP settings.

Related

SQL Server stored procedure dynamic Where condition in temporary table

I am using ASP.NET and a SQL Server database.
I have options to search values from gridview base on some criteria. The criteria are mostly independent from each other.
For example:
"where ProductType = " + Convert.ToInt32(recordType.persoRecord) +
" and AccountNumber like '%" + SearchValue + "%'";
or
"where fileid=" + File_ID + ShowSearch +
" and lower(j.CardHolderName) like '%" + SearchValue.Trim().ToLower() + "%'
There are a lot of options to search by user. I have millions of rows of data in this table, in order to fetch the data and bind it fast to gridview, I have created a stored procedure.
It works fine for fetching and binding but for searching, it's hard to manage. Due to I don't have much time, i want to configure the stored procedure to 'if there's a searching' fetch the searched data only.
Here is my stored procedure:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[SetJobsGrid]
(#FileID varchar(50),
#PageIndex int = 1,
#PageSize int = 1,
#DynamicQuery NVARCHAR(MAX),
#SearchFlag bit,
#RecordCount int output)
AS
BEGIN
DECLARE #SearchQuerySQL as nvarchar(MAX)
SET NOCOUNT ON;
select ROW_NUMBER()OVER (
order by j.creationdate asc,
j.id desc
) AS RowNumber
, j.id as 'Serial #', j.jobname as 'File Record Name',
j.RecordNumber as 'Record Number',i.issuername as'Issuer Name',p.ProductName as 'Product Name',p.productNumber as 'Product Number',
(j.AccountNumber) as AccountNumber ,j.CardHolderName as 'Card Holder Name', j.CardholdersBranchName as 'Card Holder Branch Name',
j.ShipmentBranchName as 'Shipment Branch Name', j.EmbossingCardholderName as 'Embossing Card Holder Name', j.MaskedPAN as 'PAN',
j.creationdate as 'File Record Creation Date', j.status as 'File Record Status', j.chipdatastatuserror as 'ChipDataStatus Erro',
j.chipdatastatuserrormessage as 'Error Message', j.chipdatastatus as 'Data Prepared',j.isduplicaterecord as 'isduplicate',j.isduplicatefromsamefile as 'IsDuplicateFromSameFile',
j.validationerrors , j.isworkordercreatedForCard,j.isworkordercreatedForPin,j.isworkordercreatedForCarrier,j.PersoMachineId,j.PinMachineId,j.CarrierMachineId
INTO #Results
FROM jobs j join issuer i on j.issuerid=i.id join Product p on p.id=j.productid WHERE fileid = #FileID
IF(#SearchFlag = 1)
begin
select #SearchQuerySQL = 'SELECT ' + #RecordCount + ' = COUNT(*) FROM #Results ' + #DynamicQuery
EXEC(#SearchQuerySQL)
select #SearchQuerySQL = 'SELECT * FROM #Results ' + #DynamicQuery + ' and RowNumber BETWEEN(#PageIndex -1) * #PageSize + 1 AND(((#PageIndex -1) * #PageSize + 1) + #PageSize) - 1'
EXEC(#SearchQuerySQL)
end
ELSE
begin
SELECT #RecordCount = COUNT(*)
FROM #Results
SELECT * FROM #Results
WHERE RowNumber BETWEEN(#PageIndex -1) * #PageSize + 1 AND(((#PageIndex -1) * #PageSize + 1) + #PageSize) - 1
end
DROP TABLE #Results
END
When the SearchFlag is set to true from ASP.NET, I want to fetch only searched value. #DynamicQuery set from asp for example:
WHERE AccountNumber LIKE '%" + SearchValue + "%'"
or with many different case.
When I run this stored procedure as in the above, I get an exception:
Conversion failed when converting the varchar value 'select ' to data type int
Regards
To make the stored procedure use your dynamic where statement, it is better to use sp_executesql
example:
EXEC sp_executesql
N'select * from Employees where Id = #param1',
N'#param1 int'
,#param1 = 1
for more information about dynamic query refer to the following site
SQL Server Dynamic SQL
Too long for a comment but you need to understand why the error occurs to fix it. You have this snippet in your code
select #SearchQuerySQL = 'SELECT ' + #RecordCount +
First, if you intend to assign a scalar value (e.g., #SearchQuerySQL) then you should use SET, not SELECT. That's another topic you can research at your leisure. The assignment expression that follows is where you intended to do string concatenation. Unfortunately, the interpretation of the plus sign operator varies according to datatypes involved.
What happens when the database engine encounters an operator that involves 2 different datatypes. Like any other language, one (or both) must be converted to the same type in order to perform the expressed operation. How does the engine do that? There are rules for datatype precedence. In this case, your int parameter has higher precedence and so those strings in that expression are converted to int. That fails with the error that you encountered.
If you want to write dynamic sql, you need to have an advanced understanding of tsql. You should also consider searching the internet first before trying to reinvent the wheel. Maybe Aaron's article on dynamic pagination might help - but it might be a bit much for you at this point.
And while you're mucking about with things, add some comments within the procedure declaration about the usage you intend to support. No one should have to read your code to understand what it does and how it should be used.

Query performance issue - Not in

The query below is created by someone else but is running long so need to improve the performance. Can you please suggest me a better way to do?
Select * from ps_vendor G where G.vendor_id NOT IN (SELECT vendor_id
FROM ps_voucher_line
WHERE vendor_id <> '70830'
AND cntrct_id <> ' '
AND vendor_id NOT IN (SELECT vendor_id
FROM ps_cntrct_hdr
WHERE
cntrct_type = 'AP'))
Please try with inner join condition like display below
Select G.* from ps_vendor G
inner join ps_voucher_line pvl
on G.vendor_id = pvl.vendor_id and pvl.vendor_id <> '70830'
inner join ps_cntrct_hdr pch
on (pch.vendor_id <> pvl.vendor_id and pch.cntrct_type = 'AP')
where pv.cntrct_id <> ' '
Try different variations in joining condition!!
Good is that you have sub query to verify results.

SQLite Join OperationalError

When running this SQL code with join, I got an error:
ss= 'select project.id from project_list pl '
ss+= ' LEFT JOIN project p ON pl.project_id = p.id '
ss+= ' LEFT JOIN table t ON pl.table_id = t.id '
Error is :
OperationalError: (sqlite3.OperationalError) near "table":
syntax error [SQL: 'select project.id from project_list pl
LEFT JOIN project p ON pl.project_id = p.id LEFT JOIN table t
ON pl.table_id = t.id ']
This is not where the error comes from since the SQL statement looks correct.
This is using SQL Alchemy.
If you have a table named table, you need to quote it, or it causes a parsing error. This will work:
ss= 'select project.id from project_list pl '
ss+= ' LEFT JOIN project p ON pl.project_id = p.id '
ss+= ' LEFT JOIN "table" t ON pl.table_id = t.id '
This is because table is a reserved word in SQL (e.g. create table my_table, alter table mytable, etc.), and either the SQL parser is primitive, or the spec demands that it behave this way (PostgreSQL has the same problem).
I strongly encourage you to rename table to something else, if you can, or you're going to be in for a world of hurt. In other scenarios with SQLAlchemy or other DB libraries, when you're not hand-crafting the SQL, they may not be smart enough to automatically quote the table name. This will also cause you headaches if you migrate from SQLite to another database. It's likely to confuse people reading the code.

How can I see the last SQL statement executed in Oracle database 11g r2?

I am new to oracle database.
Can someone give me an example of the steps for how to see the last statements executed on the Oracle database 11g r2?
You can use the below query to get the last sql executed based on last sql which was active in database
select ltrim(sq.sql_text)
from v$sql sq, v$session se, v$open_cursor oc
where sq.sql_id = oc.sql_id
and se.saddr = oc.saddr
and se.sid = oc.sid
and se.audsid = SYS_CONTEXT('userenv', 'sessionid')
order by oc.LAST_SQL_ACTIVE_TIME desc;
You can also use the below to find the last query executed in your session.
SELECT (SELECT t2.sql_fulltext
FROM v$sql t2
WHERE t1.prev_sql_id = t2.sql_id
AND t1.prev_child_number = t2.child_number) sql_fulltext
FROM v$session t1
WHERE t1.audsid = Sys_context('userenv', 'sessionid');
You can use the below query:
SELECT program_id, program_line#, sql_text
FROM V$SQL VS , ALL_USERS AU
WHERE (executions >= 1)
AND (parsing_user_id != 0)
AND (AU.user_id(+) = VS.parsing_user_id)
AND UPPER(AU.USERNAME) IN (UPPER('YourUser'))
ORDER BY last_active_time DESC;
if you need to know the statements of an PL/SQL object were executed then use or join with
select *
from dba_objects
where object_id = program_id
Find all sql where sql is like ....
select h.sample_time
, u.username
, h.machine
, s.sql_text
, h.*
from dba_hist_active_sess_history h
inner join v$sql s
on s.sql_id = h.sql_id
left outer join dba_users u
on u.user_id = h.user_id
where s.sql_text like 'DELETE%'
order by h.sample_time desc;
You need to be connected as sysdba user for this sql
A couple of hints:
In SQLplus, type a semicolon+ to see, and slash to execute again
In SQLdeveloper, use F8
If you mean see other users' statements then it's not possible by default.
You can configure AUDIT.
You can see some SQL statements in SELECT * FROM V$SQLAREA;
Connect as SYS user and execute the following query
select sql_text from v$sql where first_load_time=(select max(first_load_time) from v$sql) ;
select sq.PARSING_SCHEMA_NAME, sq.LAST_LOAD_TIME, sq.ELAPSED_TIME, sq.ROWS_PROCESSED, ltrim(sq.sql_text)
from v$sql sq, v$session se
where sq.PARSING_SCHEMA_NAME = 'YOUR_SCHEMA'
order by sq.LAST_LOAD_TIME desc;

Why does the 2nd T-SQL query run much faster than the first when called by Reporting Services 2005 in a web-app

With the addition of parens in the subquery, results were returned immediately in the app.
This runs slow when called by RS2005 in a vb.net / aspx web app:
SELECT
c.TeacherID, u.FName + ' ' + u.lname as Teacher, count(sb.behaviorID) as BxCount,
sb.behaviorID, b.BehaviorName, std.GradeID, gl.GradeLevel
FROM
StudentBehaviors sb
join
Classes c on sb.classid = c.classid
join
StudentDetails std on sb.studentID = std.StudentID and std.RecordIsActive=1
join
users u on c.TeacherID = u.UserID
join
Behaviors b on sb.behaviorID = b.BehaviorID
join
GradeLevels gl on std.GradeID = gl.GradeLevelID
WHERE
sb.classdate between #StartDate and #EndDate
and c.schoolid = #SchoolID
and std.GradeID=#GradeLevel
GROUP BY
c.TeacherID, sb.behaviorID, b.BehaviorName, u.lname, u.FName,
std.GradeID, gl.GradeLevel
ORDER BY
u.LName, sb.behaviorID
This runs fast:
select a.teacherid, a.teacher,a.bxcount, a.behaviorid,a.behaviorname,a.gradeid, a.gradelevel
from (
SELECT c.TeacherID, u.FName + ' ' + u.lname as Teacher, count(sb.behaviorID) as BxCount,
sb.behaviorID, b.BehaviorName, std.GradeID, gl.GradeLevel
FROM StudentBehaviors sb
join Classes c on sb.classid = c.classid
join StudentDetails std on sb.studentID = std.StudentID and std.RecordIsActive=1
join users u on c.TeacherID = u.UserID
join Behaviors b on sb.behaviorID = b.BehaviorID
join GradeLevels gl on std.GradeID = gl.GradeLevelID
WHERE sb.classdate between #StartDate and #EndDate
and c.schoolid = #SchoolID
and std.GradeID=#GradeLevel
group by c.TeacherID, sb.behaviorID, b.BehaviorName, u.lname, u.FName, std.GradeID, gl.GradeLevel
) a
order by a.teacher, a.behaviorid
These run at the same speed in a query windows in SQL Server Management Studio. Why the difference? Thanks.
You may have come across a query that has an issue with parameter sniffing, which has to do with how Sql Server tries to optimise your query execution plan but in cases when Reporting Services is involved completely messes it up and makes it run incredibly slowly.
I had a case with a report that had two complex queries of around 150 lines each but which ran in 7 seconds in my development environment - the entire report took less than 10 seconds. However, when deployed to the production SSRS server the report took more than 7 minutes and often timed out making the report unrunnable.
Most information about this issue talks about it in relation to stored procedures. Don't dismiss this because you are not using stored procedures (like I did for a long time); it is very relevant to straight Sql queries as well.
So the difference you are seeing is that Sql Server is creating two very different execution plans as the two queries are structured differently.
Fortunately, the solution is very simple: put the parameters into internal variables and use these in your query instead. I did this with my report and the production report went back to 10 seconds like the development version did in Visual Studio.
To bypass parameter sniffing for your first query you would make it look like this:
BEGIN
-- Use internal variables to solve parameter sniffing issues
DECLARE #StartDateInternal AS DATETIME;
DECLARE #EndDateInternal AS DATETIME;
DECLARE #SchoolIDInternal AS INT;
DECLARE #GradeLevelInternal AS INT;
-- Copy the parameters into the internal variables
SET #StartDateInternal = #StartDate;
SET #EndDateInternal = #EndDate;
SET #SchoolIDInternal = #SchoolID;
SET #GradeLevelInternal = #GradeLevel;
-- Now use the internal variables in your query rather than the parameters
SELECT
c.TeacherID, u.FName + ' ' + u.lname as Teacher, count(sb.behaviorID) as BxCount,
sb.behaviorID, b.BehaviorName, std.GradeID, gl.GradeLevel
FROM
StudentBehaviors sb
join
Classes c on sb.classid = c.classid
join
StudentDetails std on sb.studentID = std.StudentID and std.RecordIsActive=1
join
users u on c.TeacherID = u.UserID
join
Behaviors b on sb.behaviorID = b.BehaviorID
join
GradeLevels gl on std.GradeID = gl.GradeLevelID
WHERE
sb.classdate between #StartDateInternal and #EndDateInternal
and c.schoolid = #SchoolIDInternal
and std.GradeID = #GradeLevelInternal
GROUP BY
c.TeacherID, sb.behaviorID, b.BehaviorName, u.lname, u.FName,
std.GradeID, gl.GradeLevel
ORDER BY
u.LName, sb.behaviorID;
END;

Resources