Sp_trace_setfilter Mixing AND/OR Operators In Profiler
Jul 24, 2007
Hello, how do you setup a Profiler filter, that has mixed AND/OR operators. Thru the Profiler GUI, I don't even see how you would ask for any statement/proc with READS over 10,000 OR DURATION over 1000ms. How do you do an "OR" thru the GUI?
Forgetting the GUI and doing traces thru scripts, the @logical_operator isn't too logical, and I can't find any description for setting this parameter. If you only have one filter, it doesn't matter if you set it to 0 (AND) or to 1 (OR)... But if you want multiple filters, so one filter is Reads >= 10,000 and the other filter is Duration >= 1000ms., how do you do that? I tried it with the @logical_operator of "1" on both, but then I also got other events with a NULL value in READS.
We're SQL Server 2005 SP2 x64, and I'm playing around with server side tracing. Specifically, we're trying to audit anyone doing UPDATE on the database. We don't want to capture anything else (like user 'SELECT's), that would generate unnecessary events.
What I've done: 1) Create a trace/template in SQL profiler to capture "SQL:StmtCompleted" 2) Add a filter on 'TextData' column, using 'Like'; 'UPDATE%' 3) Profiler trace using this template works fine, I'm capturing the correct data and nothing else. 4) In the profiler tool, I did 'Export-Script Trace Definition'. This created a script file that had the following line:
5) I can run the server side trace (I'm tracing to a filename 1.trc on the server). Unfortunately - here's the issue - when I open the trace file using profiler, it looks like I have captured all SQL:StmtCompleted events, even the ones that I did not want (like SELECT statements). The filter is not working.
My sales are broken into two different major categories: retail and internet. Rather than create two identical fact tables (ala AdventureworksDW) I created on fact table with a dimension that slices by retail or interent. I use that dimension as a parameter on nearly every one of my reports. The use can get retail, internet or both. So far, so good.
Now I need to create a report that shows retail sales and internet sales in adjacent columns on the same report. Is there a way to filter individual columns in a table? Or will I have to rethink how I store my data in the cube?
I've encountered this problem multiple times in the past and I have a solution but wonder if there might be a more elegant method of achieving the same result...
Take the following example:SELECT * FROM [User] LEFT OUTER JOIN [Profile] ON [Profile].[UserId] = [User].[UserId] INNER JOIN [Department] ON [Department].[DepartmentId] = [Profile].[DepartmentId]
Users may or may not have a profile (but never more than one). A profile may or may not have a department (but never more than one).
Now, this will return only users that have a profile even though an outer join has been used. What I really want is to return all users and include their profile and department details but only when the profile has a department.
The solution I have used in the past is:
SELECT * FROM [User] LEFT OUTER JOIN ( SELECT * FROM [Profile] INNER JOIN [Department] ON [Department].[DepartmentId] = [Profile].[DepartmentId] ) [ProfileDepartment] ON [ProfileDepartment].[UserId] = [User].[UserId]
The trouble here is that I've lost the ability to reference department and profile independantly in the outer query. Also, more complex scenarios can also become horribly complex if this needs to be done multiple times in the same query.
I could do this:SELECT * FROM [User] LEFT OUTER JOIN [Profile] ON [Profile].[UserId] = [User].[UserId] AND [Profile].[DepartmentId] IS NOT NULL LEFT OUTER JOIN [Department] ON [Department].[DepartmentId] = [Profile].[DepartmentId]
But again I feel that the intention is not at all clear. I want to inner join department to profile because I'm only interested in profiles with a department and departments referenced by a profile.
I would like to be able to specify that the departments should be inner joined to profiles and whichever profiles remain get outer joined to users whilst retaining department and profile as seperate entities within the query.
Is there any way to use brackets to indicate an order of precedance to the logical joins within the from clause?
How do I create a query that emulates a mix of aggregate & ‘non-aggregate’ expressions. I am using the query as the rowsource for a list box in Access.
Here is my query: strSql = "SELECT tblTestHeader.TestHdrUniq, tblTestHeader.TestDate, " _ & "'" & Forms("frmCompanySearch").[lstCompanySrch].Column(2) & "'" _ & " + ' ' + tblLoadCell.Abbrev + ' ' + tblTestHeader.CertNumSequence AS CertNum, " _ & "tblLoadCell.Description AS LoadCell, " _ & "tblTestType.Description AS Test, " _ & "tblTester.Sname + ', ' + tblTester.Gname AS Tester " _ & "FROM tblTestHeader INNER JOIN tblLoadCell ON " _ & "tblTestHeader.LoadCellUniq = tblLoadCell.LoadCellUniq INNER JOIN " _ & "tblTester ON " _ & "tblTestHeader.TesterUniq = tblTester.TesterUniq INNER JOIN " _ & "tblTestType ON " _ & "tblTestHeader.TestTypeUniq = tblTestType.TestTypeUniq " _ & "WHERE CompanyUniq = " _ & Forms("frmCompanySearch").[lstCompanySrch].Column(1) _ & " ORDER BY tblTestHeader.TestDate, CertNum"
I want to include another column: max(tblTestDetail.CertChar) as LastChar but must have all or no aggregate expr. What is work around for this ?
I want to create a filtered view according to some information provides. for example I want to create in form 2 check boxes male and female and when either both or one of them is unchecked, the query filters out the unchecked content from view according to the other filtering conditions.
the exact thing I need is: a text box for string looking (in a specific column). male & female checkboxes. two datetime textboxes to specify a range to focus in.
it is very important to me, so if you misunderstood my question, please contact me.
I have an update command with 7 parameters, but at run time the order to the parameters gets mixed up. I'm using a stored procedure. At first I have the command type set to text, and was calling it using EXEC spName ?,?,?,?,?,?,? I then named each of the parameters and set their sources. The parameters are like this (samepl name, then source, then type): A : QueryString - intB: Control - intC: Control - intD: None - intE: None - decimalF: Control - datetimeG: Control - datetime At run time I was getting an error that an integer couldn't be converted to date time. So I put a breakpoint in the Updating event and then looked at the parameters prior to update. This is how they looked (Parameter index, paramter name): [0] A[1] B[2] D[3] E[4] F[5] G[6] C It didn't maek any sense. Do, I deleted all of the paramters and readded them. That didnt' work. Then I changed the command to StoredProcedure and refreshed the parameters from the stored proc and it brought them in the right order, but the problem remains the same. I looked at the page source, and there are no indexes in the page source, but the parameters are listed in the proper creation order, as follows:<UpdateParameters><asp:QueryStringParameter Type="Int32" Name="PROJ_ID" QueryStringField="pid"></asp:QueryStringParameter><asp:ControlParameter PropertyName="SelectedValue" Type="Int32" Name="TASK_UID" ControlID="fvTask"></asp:ControlParameter><asp:ControlParameter PropertyName="SelectedValue" Type="Int32" Name="ASSN_UID" ControlID="gvResources"></asp:ControlParameter><asp:Parameter Type="Int32" Name="RES_UID"></asp:Parameter><asp:Parameter Type="Double" Name="Work"></asp:Parameter><asp:ControlParameter PropertyName="Text" Type="DateTime" Name="Start" ControlID="TASK_START_DATETextBox"></asp:ControlParameter><asp:ControlParameter PropertyName="Text" Type="DateTime" Name="Finish" ControlID="TASK_FINISH_DATETextBox"></asp:ControlParameter></UpdateParameters> No mater what I do, at run time ASSN_UID is always the last parameter. I've also run a SQL trace to see how it is actually being executed, and sure enough, its passing the value for ASSN_UID as the last parameter, which obviously doesn't work. Any ideas as to why this would happen or how to fix it? (I guess I can reorder the patameters in the stored proc to match how they are being passed, but still, that wouldn't be a very comfortable solution, since it could perhaps revert at some point or something)
I'm trying to populate a table of pending emails. The problem is I need to populate the email field using a select statement but the message field with static text. Can this be done or is another approach more prudent? What I have is below but is kicking errors:DECLARE @msg varchar(300) SET @msg = 'New users have applied for accounts. Please review their information.'IF @Type='CreateUserApply' INSERT INTO cdds_Email (Address,Message)VALUES (SELECT M.EmailFROMdbo.aspnet_Membership MINNER JOINdbo.aspnet_UsersInRoles UINNER JOINdbo.aspnet_Roles RON U.RoleId = R.RoleIdON U.UserId = M.UserIdWHERER.RoleName = 'Manager',@msg)
As part of the logging process for data input, I want to update two fields in a logging table. The first is a datetime, derived from looking up the maximum value in another table (the table I've just imported), and the second is an integer - the number of rows captured in a variable during the task.
I can do this in two separate Execute SQL tasks as follows:
Task 1 syntax
DECLARE @maxDate datetime SELECT @maxDate = max(dtLastChangedDate) FROM dbo.tblCancel_RAW
UPDATE dbo.tblLogging SET PreviousFilterValue = CurrentFilterValue, CurrentFilterValue = ISNULL(CAST ( @maxdate as varchar(25)),CurrentFilterValue), DateSourceTableLastRead = GetDate(), RowsReturned= -1 WHERE SourceTableName = 'cancel'
Task 2 Syntax, with the variable user::rowsimported mapped to parameter 0
UPDATE dbo.tblLogging SET RowsReturned= ? WHERE SourceTableName = 'cancel'
However I cannot make this work with a single SQL statement such as
DECLARE @maxDate datetime SELECT @maxDate = max(dtLastChangedDate) FROM dbo.tblCancel_RAW
UPDATE dbo.tblLogging SET PreviousFilterValue = CurrentFilterValue, CurrentFilterValue = ISNULL(CAST ( @maxdate as varchar(25)),CurrentFilterValue), DateSourceTableLastRead = GetDate(), RowsReturned= ? WHERE SourceTableName = 'cancel'
because no matter how I try to map the parameter (0,1,2,3,4 etc) the task fails.
Is this behaviour by design, is it a bug, or is there something I've missed?
I have two different roles, each one with a dax filter. One is for filtering users that access by Excel, and other for filtering users that access by Reporting Services, respectively:
To create only one role that serves Excel and Reporting Services users, is it viable to use only the || (OR) operator?, is there any other regard i should take?
Hi I just got a paging procedure from the internet and it’s working just fine, but I would like to return the numbers of pages too. So I used the Count() function to retrieve all records on the table and divided by the page size, but even I doing with float number, this is returning a integer number. I just started with SQL Server, does some knows what is wrong with the following code? or knows a better way to do it.
Declare @Records int, @Pages float, @hey int
Set @Records = (Select Count(*) as 'Friends' From friends
What am I missing? I can only select 1 operator to inform. Should an 'operator' be redefined to have multiple addresses, if so, how should they be delimited?
I have an implementation of the UDT - 3-dimentional vector. In my code I have implemented add, subtract and multiply methods for the type. I have also implemented overloaded operators for +/-/* in my C# code. Those overloaded operator are working as expected in C# tests. However when I€™m trying to use +/-/* operators in T-SQL over my UDT it returns the following error:
Invalid operator for data type. Operator equals add, type equals Vector.
The following fragment does work:
DECLARE @v1 Vector, @v2 Vector, @v3 Vector;
SELECT @v1 = CAST('1,1,1' as Vector), @v2 = CAST('2,2,2' as Vector)
SELECT @v1 = CAST('1,1,1' as Vector), @v2 = CAST('2,2,2' as Vector)
SELECT @v1 'v1', @v2 'v2', @v1+@v2 'v1 + v2'
I guess that SQL Server is not aware of the operators€™ overload I have implemented in the C# code. Is there any way to instruct SQL Server to use overloaded operators in the T-SQL so the code will look naturally @a + @b instead of @a.[Add](@b) and as a result use standard summary functions SUM() instead of writing user defined aggregate function for the Vector type field?
I'm not sure which section this really comes under and I think 'availability/disaster recovery' is probably the most applicable, sorry if it isn't.
I have SQL Server 2005 set-up and about 50 jobs listed, now, these jobs were configured before an operators with alerting by email was set-up... so, none of the jobs when fail alert an operator.
Is there any way I can automate a solution so if any job fails a designated/or default operator will be emailed and told what happened? Or would I need to edit each job manually to set this?
Code below: [Code SQL] USE TestWarehouse IF ('dbo.TestItems') IS NOT NULL DROP TABLE [dbo].[TestItems]; GO CREATE TABLE [dbo].[TestItems] ( TestItem int not null IDENTITY (1,1)
I'm trying to put an expression into a view query column. I've already created a column which contains the results of a calculation in the form of an expression. What I don't know how to do is use comparison operators to return a boolean value for display. I'll give some examples of what I'm trying to do, using literal values just to simplify things...
So say I want to display the result of an expression in a view query column, as a boolean value (or BIT), as True or False. I've tried putting the following expressions into the column and none work:
4 < 5: Access converts this to the string '4 < 5' and it's just displayed as a string.
CAST( '4 < 5' AS BIT ): When run, the query displays the error 'Syntax error converting the varchar value '4 < 5' to a column of data type BIT.
Although I'm using Access 2003, It's just a front end for a SQL Server 2000 database. The actual SQL statement containing the latter SQL function is:
SELECT dbo.Tapes.No, dbo.Tapes.Status, dbo.Tapes.LastWrittenDate, dbo.Tapes.Pool, dbo.Tapes.Location, dbo.TapeJobs.No AS Expr1, dbo.TapeJobs.JobNo, dbo.TapeJobs.TapeNo, dbo.Jobs.No AS Expr2, dbo.Jobs.Date, dbo.Jobs.Successful, dbo.Jobs.RetentionRule, dbo.RetentionRules.No AS Expr3, dbo.RetentionRules.Name, dbo.RetentionRules.Description, dbo.RetentionRules.RetentionPeriod, dbo.RetentionRules.RetentionCycles, dbo.Jobs.Date + dbo.RetentionRules.RetentionPeriod AS AgedJob, CAST('4 < 5' AS BIT) AS Expr4 FROM dbo.RetentionRules INNER JOIN dbo.Jobs ON dbo.RetentionRules.No = dbo.Jobs.RetentionRule RIGHT OUTER JOIN dbo.Tapes RIGHT OUTER JOIN dbo.TapeJobs ON dbo.Tapes.No = dbo.TapeJobs.TapeNo ON dbo.Jobs.No = dbo.TapeJobs.JobNo
I'm new to SQL. I think the CAST function is the way forward, but I just don't know how to force it to resolve the expression '4 < 5'.
I am trying to create a stored procedure that filters some customers. The field in wich I am trying to apply the filter is the age field. The problem is that I need to be able to select the comparison operator =,<,>,=<,>=,<>. I was trying to do it with the following code:
Select CustomerName From Customer Where (CustomerAge & @Operator & @Age)
But sql Server shows an error telling me that @Operartor couldnt be converted to int.
I dont know if I am in the right track or way off, how is this done?
I want know where can I find information about valid expresion types for each one of de Arithmetic Operators, Bitwise Operators, Comparison Operators, Logical Operators, Unary Operators in SQL server. I want something like this.
for (+) ADD, syntaxis -> expression + expression
expression Valid? result type ----------------------------------------------------------------- int + int ok int int + bigint ok bigint char + char ok char <- (+) works like concatenation char + int ok char??? image + bit error - binary + int ok binary???
for (*) MULTIPLY, syntaxis -> expression * expression
expression Valid? result type ----------------------------------------------------------------- int * int ok int int * bigint ok bigint char * char error - char * int error - image + bit error - binary + int ok binary????
for (<) LESS THAN, syntaxis -> expresion < expression
expression Valid? result type ----------------------------------------------------------------- int < int ok bit??? char < char ok bit??? char < int ok bit??? image < bit error -
Hi all, real basic question: I can't seem to find a basic reference that tells me the syntax and allowable values of parameters in common functions such as Format or CDate when editing a Field Expression in Visual Studio (Report Definition Language?). Where would I start?
For example, I've discovered that the Format function "Returns a string formatted according to instructions contained in a format String expression.", and the string expression can have values like "D" and "d" which produce different results, but where would I find out what the allowable string expressions are and their meaning?
I have also been guessing at the syntax of the CDate command with no luck. I need a reference that tells me what the different function parameters mean.
I am in the midst of writing a query to return a range of product BIN LOCATIONS from a warehouse stock levels program.I know the start and end BIN LOCATIONS for the warehouse, e.g.: Start - #00000, and End - Z10000.However I cannot hard code these into the program, instead I want my operator to designate the first letter of both the start and end BINS locations, and then hit the 'go button'.Towards this end I have declared a couple of variables in my SQL, as follows -
Code: declare @strBin varchar(10) set @strBin = '' if @strBin = '' set @strBin = '#%'
declare @endBin varchar(10) if @endBin = '' set @endBin = 'z%'
My challenge is writing a relevant WHERE clause for my select statement, I have tried the following -
Code: where BINLOCAT.BINLABEL between @strBin and @endBin order by BINLOCAT.BINLABEL
Whilst the clause above does not cause any errors, neither does it return any results.My first thought is that the BETWEEN operator does not accept wildcards. But if this is correct then how do I go about allowing an operator to enter the start, and end BINS without typing the entire BIN string (e.g.: #00000)? I have tried >= @strBin and <= @endBin, but I am having a similar issue with no errors, and no data returned.
We can use comparison operators with strings as well. Hence, I tried to use the following query on a SQL Server 2012 instance with the sample AdventureWorks2012 database (the collation of the database and of the column is the default:
SQL_Latin1_General_CP1_CI_AS):
USE AdventureWorks2012 ; GO
--Returns 5 records SELECT pp.Name FROM Production.Product AS pp WHERE pp.Name >= N'Short' AND pp.Name <= N'Sport' ; GO
The query only returns 5 records. This despite the fact that the search is an inclusive search and the Production.Product table contains records that begin with "Sport".
Now, when I replace "Sport" with "Sporu" (just moving one character up in the alphabet to verify whether characters after the word have any impact on the search) gives me 8 records.
USE AdventureWorks2012 ; GO
--Returns 8 records SELECT pp.Name FROM Production.Product AS pp WHERE pp.Name >= N'Short' AND pp.Name <= N'Sporu' ; GO
What's going on inside of SQL Server that allows it to fetch "Short-Sleeve Classic Jersey" for the starting word "Short" but prevents it from fetching "Sport-100 Helmet" for the ending word "Sport" despite the search being an inclusive search?
I have a problem at the moment, where the client wants to be able to type in a custom algebraic formula with add/minus operators, and then to have this interpreted, so that the related datasets are then added and returned as a single dataset.
An example would be having a formula stored of [a] + [b] - [c]
and if I were to write the SQL to apply that formula, I might write something like (let's assume 1:1 relationships with the ID's)
select a.a + b.b - c.c as [result] from z inner join tblA a on z.id = a.id inner join tblB b on z.id = b.id inner join tblC c on z.id = c.id
The formula can change though, maybe things like:
[a] + [b] + [c] + [d] [a] + [b]
The developer before me wrote something SQL-based where they parsed the string and assigned each value of the formula as either positive or negative (e.g A is positive, B is positive, C is negative, now sum the datasets to get the result), and then created one large table of values then summed them. This does (kind of) work, I'm just contemplating potential alternatives, as it is quite a slow process, and feels like it is quite convoluted, when I get into the details. If I were to do something like this in SQL, I'd normally want each part of the expression to be a column, and then to just apply the operators, but because the formula can change, then the SQL would need to be somehow dynamic for this approach.
DECLARE @Teams AS TABLE(Team VARCHAR(3)) INSERT INTO @Teams SELECT 'IND' UNION SELECT 'SA' UNION SELECT 'AUS' select Team from @Teams where Team > 'AUS'
[code]....
co-relation between comparison operators in WHERE Clause and the respective output.
CREATE PROCEDURE dbo.spinb_CheckYN @FnNameYN varchar(50), @InvLineID int, @FnBit bit output AS
declare @SQL varchar(8000)
set @SQL = ' if dbo.' + @FnNameYN + ' (' + convert(varchar(31),@InvLineID) + ')) = 1 set @FnBit = 1 else set @FnBit = 0'
exec (@SQL) GO
Obviously; @FnBit is not defined in @SQL so that execution will not work. Server: Msg 137, Level 15, State 1, Line 4 Must declare the variable '@FnBit'. Server: Msg 137, Level 15, State 1, Line 5 Must declare the variable '@FnBit'.
So; is there a way to get a value out of a Dynamic SQL piece of code and get that value INTO my OUTPUT variable?
My many thanks to anyone who can solve this riddle for me. Thank You!
Sigh: For now, it looks like I'll have a huge string of "IF" statements for each business rule function, as follows: Hopefully a better solution comes to light.
------ Vertical Build1 - Std Vanes ----------- if @FnNameYN = 'fnb_YN_B1_14' BEGIN if dbo.fnb_YN_B1_14 (convert(varchar(31),@InvLineID) ) = 1 set @FnBit = 1 else set @FnBit = 0 END
------ Vertical Build1 - Scissor Vanes ----------- if @FnNameYN = 'fnb_YN_B1_15' BEGIN if dbo.fnb_YN_B1_15 (convert(varchar(31),@InvLineID) ) = 1 set @FnBit = 1 else set @FnBit = 0 END . . . etc.
Can only member in the System Administrators role use the SQL Profiler’s? Is there any other role or way to allow user to use this tool other then adding them to this role? Thanks you
Does anybody have any idea if there is a bug in SQL 7.0 where running multiple traces causes the SQL 7.0 to crash ?? This is running in a clustered environment.