Using LIKE Operator In An O BY Clause On SQL Server 2K5
Oct 3, 2007
I am migrating a classic ASP application that ran on Access to ASP.NET with SQL Server 2005 DB. I am having some trouble getting a query to work. It runs part of our courses section of the web site.
SELECT CREDIT_DATA_LOCCODE.Loc_Code, CREDIT_DATA_LOCCODE.Loc_Name, CREDIT_DATA_COURSE.Fiscal, CREDIT_DATA_COURSE.Term, CREDIT_DATA_COURSE.Major_Code, CREDIT_DATA_COURSE.Status_Code, CREDIT_DATA_COURSE.Course_Number1, CREDIT_DATA_COURSE.Course_Number2, CREDIT_DATA_COURSE.Section_Number, CREDIT_DATA_COURSE.Course_Title, CREDIT_DATA_COURSE.Credits, CREDIT_DATA_COURSE.Credits_Other, CREDIT_DATA_COURSE.Web_Website_link, CREDIT_DATA_COURSE.Web_Description, CREDIT_DATA_COURSE.Web_Instructor_1, CREDIT_DATA_COURSE.Web_Instructor_2, CREDIT_DATA_COURSE.Web_Location, CREDIT_DATA_COURSE.Web_LocCode, CREDIT_DATA_COURSE.Web_Dates, CREDIT_DATA_COURSE.Web_ETV_Dates_Times, CREDIT_DATA_COURSE.Web_ETN_Dates_Times, CREDIT_DATA_COURSE.Web_Times, CREDIT_DATA_COURSE.Enrollment_Limit, CREDIT_DATA_COURSE.Web_Icon_1, CREDIT_DATA_COURSE.Web_Icon_2, CREDIT_DATA_COURSE.Web_Note, CREDIT_DATA_COURSE.Web_Prereq, CREDIT_DATA_COURSE.Web_Special_Message, CREDIT_DATA_COURSE.Web_Alt_Major_Code, CREDIT_DATA_COURSE.Web_Alt_Course_Number1, CREDIT_DATA_COURSE.Web_Alt_Course_Number2, CREDIT_DATA_COURSE.Web_Alt_Section_Number, CREDIT_DATA_COURSE.Deleted, CREDIT_DATA_COURSE.Update_Date
FROM CREDIT_DATA_LOCCODE INNER JOIN CREDIT_DATA_COURSE ON CREDIT_DATA_LOCCODE.Loc_Code = CREDIT_DATA_COURSE.Web_LocCode WHERE (CREDIT_DATA_COURSE.Fiscal = N'078') AND (CREDIT_DATA_COURSE.Term = N'10') AND (CREDIT_DATA_COURSE.Status_Code <> 5) ORDER BY CREDIT_DATA_LOCCODE.Loc_Name, CREDIT_DATA_COURSE.Major_Code, CREDIT_DATA_COURSE.Course_Number1, CREDIT_DATA_COURSE.Section_Number
But when I run this query with the ORDER BY Clause in place against the SQL 5 tables Sheila dumps into I get this Error:
We have a column in table which represents operator like
>,>=,<,<=, =
And we want to use it in sql query depending on the condition for each id column in table
Our table is
id int operator nchar(10)
1,>= 2,<= 3,> 4,< 5,= . . . .
I need to use the operator from table into where clause for using condition for all the ids instead of single operator. I tried it using the dynamic query but how can we execute it for each id in single query.
Insert into deltavalues values ('1002', 2000,5000) Insert into deltavalues values ('1003', 1000,0) Insert into deltavalues values ('1004', 500,0) Insert into deltavalues values ('1005', 1000,2000)
--I have below query , basically getting emnployee table balance between deltavalues table baseval column and highval column
select * from employee e join deltavalues d on e.planid = d.planid where e.balance between d.baseval and d.highval
but here what i am requesting you is how can i change the highvalue to not include if it is 0
for example above example plan 1003, 1004 has highbal as 0 so i want to write a query to get employee data between 1000 and anyvalue (> 1000 - no limit)
same way for 1004 between 500 and no end values (infinity)
I'm trying to get a tree structure from a table. Ex : Security table. How can I accomplish that task in SQL Server?? I will do it using Level and connect by operators in Oracle to accomplish the task. Your reply in this regard is highly appreciated. Thanks, Navy
I have a text box on a web application that allows the user to type what words they want to look. In the first version of the web application the user wrote the words he wanted and was wanted on the table by CONTAINS various words with the OR operator . What I wanted now was to allow the user to write several words, but with a particularity . The words that were inside '' was like a word.
I wish my transform variable, so that adding the OR operator, and the words within the quotes are not to put the OR.
ALTER PROCEDURE @Product = ' 'ORANGE LEMON' BANANA APPLE 'PEACH PEAR' ' AS
-- I WANT TRANSFORM THE WORDS @PRODUCT = 'ORANGE LEMON' OR BANANA OR APPLE 'PEACH PEAR'
What I meant was that even using the full-text functionality. I'm using CONTAINS . But before the CONTAISN was :
SELECT Description FROM Production.ProductDescription WHERE CONTAINS ( Description, PRODUCT )
Since PRODUCT and was researched by words such as ORANGE LEMON OR OR OR BANANA APPLE OR PEAR OR PEACH .
What is wanted now the words that come from the WEB application within '' stay as if it were the AND operator then was :
how to use like operator select statement to retrieve multiple column names in sql server DB...for ex: I have a table say employees where in I want to get all column names like emp_,acc_ etc using '%' And what is this below query used for?
SELECT column_name as 'Column Name', data_type as 'Data Type', character_maximum_length as 'Max Length' FROM information_schema.columns WHERE table_name = 'tblUsers'
I have a problem, i am upgrading a system that uses Oracle databases for using SQL Server 2005 databases. The thing is that the operator (+) (involved in many queries) is from Oracle and operators(*= and =*) are not supported in SQL Server 2005 (and not comply with the Ansi standard) i need help translating these queries. An example would be like this:
SELECT ...
FROM IBA_MPACCIONESXREQ, IBA_MPPERMISOS, IBA_MPENTIDADES, IBA_MPREQUERIMIENTOS, IBA_MPPROCEDENCIAS, IBA_LOCALIZACIONES, IBA_MPPROCEDXLOC, IBA_USUARIOS
WHERE IBA_LOCALIZACIONES.ID_LOCACLIZACION = IBA_MPPROCEDXLOC.ID_LOCACLIZACION AND IBA_MPPROCEDENCIAS.IDPROCEDENCIA = IBA_MPPROCEDXLOC.IDPROCEDENCIA AND IBA_MPREQUERIMIENTOS.IDPROCEDENCIALOCALIZACION = IBA_MPPROCEDXLOC.IDPROCEDENCIALOCALIZACION AND IBA_MPENTIDADES.IDENTIDAD (+) = IBA_MPPROCEDXLOC.IDENTIDAD
AND IBA_MPPERMISOS.IDPERMISO (+) = IBA_MPPROCEDXLOC.IDPERMISO AND IBA_MPACCIONESXREQ.IDREQUERIMIENTO = IBA_MPREQUERIMIENTOS.IDREQUERIMIENTO AND IBA_MPACCIONESXREQ.USERNAME = IBA_USUARIOS.USERNAME
ORDER BY ...
I didnt include the SELECT and ORDER BY text because i dont think its important. Also i know that you have to move the outer joins to the FROM clause but i didnt manag to get it. Could you help me? thank you in advance.
I am trying to create an alert when there are more than 2500 connections to our ailing SQL Server.However, for now, I need to restart the SQL server service because users begin complaining they can't connect.
1) I created an operator - me.
2) I created a job which runs a query.
INSERT INTO Sessions_alert SELECT host_name, program_name, login_name, count(c.session_id ) num_sessions, getdate() FROM sys.dm_exec_connections c JOIN sys.dm_exec_sessions s on c.session_id = s.session_id GROUP BY host_name,program_name,login_name ORDER BY 4 DESC
3) I created an alert - included the job from above. Type performance condition alert. Object - SQL Server General Statistics. Counter - User connections.Alert if counter rises above 50. Just testing. I really want to know when it gets past 2500.
4) I've set the alert to email and delay is between responses 2 minutes.
It history tables says number of occurences is 18964. However, I don't receive an email.
Shouldn't the alert send an email? Do I need to include email code in the job?
I've been working with Database Mail for some time but I haven't seen this one before. I have a maintenance plan that does the following:
1. Check database integrity On Success: 2. Perform backups On Success: 3. Perform a maintenance cleanup On Success: 4. Notify operator of success
Steps 1 - 3 are also linked (via On Failure arrows) to a singular Notify Operator of Failure task.
The maintenance plan does exactly what I want it to, and if everything goes correctly, it successfully sends an email to an operator.
If steps 1 - 3 fail, the job ends in an error state, but does not trigger the Notify Operator of Failure task.
I was able to recreate the problem by creating another maintenance plan on the same instance with the same steps. Its "Notify Operator" on failure task also doesn't work.
It occurs to me that maybe I'm missing something, so here's some of the details of my SQL server:
SQL 2008 + SP1 (10.0.2531) x64 on Windows 2008 R2 DB Mail profile is public and default
I do have a slightly unusual profile, in that it uses two accounts:
1. A connection to a SharePoint SMTP service (where it catches emails directed at document libraries)
2. A connection to a UNIX-based smtp server (which routes mail to regular mailboxes and my SQL DBA mailing list)
The Profile will attempt to send to the SharePoint server first. The SharePoint server does not relay. If the document library email address doesn't exist, SQL will raise a warning (in the Database Mail log) and the profile will use the second account on the list, which is a real mail server and can relay the message to any mailbox.
It works really well, actually. When the maintenance plan completes successfully, the message is sent to the drop folder on the SharePoint server, and SharePoint routes the email to the correct library, and we have a central archive of all DB Mail notifications.
But if the job fails (for example, if the backup disk is out of space), none of this happens. According to the log, the job doesn't even try to send a notification. Looking at the DBMail log, the Mail service does not start. No email is delivered to the drop folder of the receiving SMTP server. So I don't think my Database Mail configuration is the problem here. It is apparently something to do with the way the job itself handles errors.
I have 8 fields - I have requirement to concatenate using '+' operator with semicolon delimiter but issues is in the
Output I get semicolons for the fields that are empty below is my code :
------------- case when [SLII Request Type] ='Job Posting' and [SmartLaborII Request Status] like 'Pending Approval (Level 4%' and [New Extension or Replacement Audit Flag] like 'FLAG%' then 'Reject – New, Extension, Replacement invalid entry' --'it is jp' else '' end as [ES Fully approved data 1], case
Does anyone have any basic, simple scripts of sp's that I can give mycomputer operators to use to monitor for serious conditions on our sqlservers? We are new in the ms-sql arena, a small shop and we cantreally purchase any tools to monitor these servers, but we need somebasic checks that we can use to make sure a server is performing in areasonable fashion, no blocks, cpu<xx%, memory not pegged, IO working,etc...and we need to be able to do this without bugging ourprogrammers every time we are wondering why things are slowwnig down.We are a split shop between as400s and sql servers, and our operationsstaff has no problem performing this type of duty on the 400s. I thinksince the sql servers are so easy to deploy into production, the ideaof how to monitor these things health got lost in the shuffle andallowing the programmers to do it just serves to destabilize ourenvironment.Please help! Our shop has turned to chaos since we went live withMSSQL centric applications and everytime one programmer "resolves anissue" some other programmers application starts to act up.
I have a quite big SQL query which would be nice to be used using UNION betweern two Select and Where clauses. I noticed that if both Select clauses have Where part between UNION other is ignored. How can I prevent this?
I found a article in StackOverflow saying that if UNION has e.g. two Selects with Where conditions other one will not work. [URL] ....
I have installed SQL Server 2014 and I tried to use tricks mentioned in StackOverflow's article but couldn't succeeded.
Any example how to write two Selects with own Where clauses and those Selects are joined with UNION?
Hi, can anyone shed some light on this issue?SELECT Status from lupStatuswith a normal query it returns the correct recordcountSELECT Status from lupStatus GROUP BY Statusbut with a GROUP By clause or DISTINCT clause it return the recordcount= -1
ON dbo.Track_ID.SM_ID = dbo.transactions.sm_session_id
GROUP BY dbo.Track_ID.TrackID
)
) Once moved to SQL Server 2005 the statement would not return and showed SOS_SCHEDULER_YIELD to be the waittype when executed. This machine is SP1 and needs to be upgraded to SP2, something that is not going to happen near time.
I changed the SQL to the following, SQL Server now runs it in under a second, but now the app is not functioning correctly. Are the above and the following semantically the same?
UPDATE dbo.Track_ID
SET dbo.Track_ID.Processed = 4 --Regular 1 leg call thats been completed
I am trying to find all affiliates that have more commissions from thisweek to the prior week. The problem is in the having part where"aff2.affiliateid = aff.affiliateid". SQL Server just doesn't liketrying to use "aff.affiliateid" to refer to the parent table.The error I get is "Invalid column name 'Col1010'.", but ONLY on thesql01 box; it runs correctly on the box where the affiliate databaseis, sql02.If I get rid of the alias of "aff" and use the full path, I get theerror, "The number name 'sql02.affiliates.dbo.affiliates_sum' containsmore than the maximum number of prefixes. The maximum is 3."Is this just a SQL bug, or is there a fix?declare @date datetime ; set @date = '2/3/05'select affiliateidfrom sql02.affiliates.dbo.affiliates_sum affwhere day >= @date - 7 and day < @dategroup by affiliateidhaving sum(lead_commissions) > (select sum(lead_commissions + sales_commissions) as totalfrom sql02.affiliates.dbo.affiliates_sum aff2where day >= @date - 14 and day < @date - 7and aff2.affiliateid = aff.affiliateidgroup by affiliateid)
1) Rows ordered using textual id rather than numeric id
Code Snippet select cast(v.id as nvarchar(2)) id from ( select 1 id union select 2 id union select 11 id ) v order by v.id
Result set is ordered as: 1, 11, 2 I expect: 1,2,11
if renamed or removed alias for "cast(v.id as nvarchar(2))" expression then all works fine.
2) SQL server reject query below with next message
Server: Msg 169, Level 15, State 3, Line 16 A column has been specified more than once in the order by list. Columns in the order by list must be unique.
Code Snippet select cast(v.id as nvarchar(2)) id from ( select 1 id union select 2 id union select 11 id ) v cross join ( select 1 id union select 2 id union select 11 id ) u order by v.id ,u.id
Again, if renamed or removed alias for "cast(v.id as nvarchar(2))" expression then all works fine.
It reproducible on
Microsoft SQL Server 2000 - 8.00.2039 (Intel X86) May 3 2005 23:18:38 Copyright (c) 1988-2003 Microsoft Corporation Developer Edition on Windows NT 5.1 (Build 2600: Service Pack 2)
and
Microsoft SQL Server 2005 - 9.00.3042.00 (Intel X86) Feb 9 2007 22:47:07 Copyright (c) 1988-2005 Microsoft Corporation Developer Edition on Windows NT 5.1 (Build 2600: Service Pack 2)
In both cases database collation is SQL_Latin1_General_CP1251_CS_AS
If I check quieries above on database with SQL_Latin1_General_CP1_CI_AS collation then it works fine again.
Could someone clarify - is it bug or expected behaviour?
Hi all,One of our companies is having problems with a query on a linked server.They have two servers, serverA and serverB. On serverA they have set up alinked server to serverB.Query: select * from oas_company where code = 'TEST'If I look on serverB via Profiler the query is executed without the wherestatement.Query: select * from oas_company where tstamp = 0Again via profiler I can see that the where statement is now included. Thetstamp field is a numerical field, the code field is a text field (don's askme why)So it looks like if there is a selection on a text field (varchar) the wherestatement is not included.For the above selection this is not a problem as this table only contains10 - 20 records. However the real problem is on the oas_balance table. Itshould only return 3 records, but because it skips the where statement, itreturns 10.000.000 records.Any idea? I know the default collations are different on both servers, couldthat be the cause of the problem? And if so, what could I do to overcomethis problem?Any suggestions would be greatly appreciated.BoB
From MS Dynamics NAV 2013 I get a lot of querries that have a where clause like this:
where [Field1] like @p1 and [Field1] < @p2. Field1 is the only primary key field and clustered index. The query also has a TOP 50 clause. @p1 is always a "Starts-With"-value (something like N'abc%').
The query plan uses a clustered index seek but the number of reads look more like a clustered index scan.
Depending on the table size I see 1M or more reads for these querries.
If I rebuild the query in SSMS, but replace the paramerters with actual values I only see a few reads.
I was able to reproduce the issue with a temp table. See code below.
Is there a way to make SQL Server use another strategy when using the parameterized query?
SQL Server Version is 11.0.3401. if object_id('tempdb..#tbl') is not null drop table #tbl; create table #tbl ( [No] nvarchar(20) ,[Description1] nvarchar(250)
Right now I have to do something like this and it is time consuming every time I have to query a specific table...
SELECT lots_of_columns FROM table WHERE (column5 = '1' OR column6 = '1' OR column7 = '1' OR column8 = '1' OR column9 = '1' OR column10 = '1' OR column11 = '1' OR column12 = '1') AND other_query_critiera_here
Typing out the OR statement gets long, time consuming and prone to errors because that first where line with all the ORs can sometimes have 20+ ORs in it. As some insight, the columns are text columns, sometimes they have data, sometimes they are NULL. Sometimes they have the same data (i.e., column5 and column6 and column12 could both have '1' as values).
I am working to move an application from MySQL to SQL Server. The person who developed the MySQL application has little database experience, and took some shortcuts that the lax nature of MySQL allows. One query with which I am struggling looks something like this:
SELECT StartTime + Offset, min(Sensor), max(Sensor) FROM SensorData WHERE SensorID = @SensorID AND StartTime + Offset > @BeginTime AND StartTime + Offset < @EndTime GROUP BY (StartTime + Offset) / 100 ORDER BY StartTime + Offset
What we are trying to accomplish is to return minimum and maximum sensor values over a number of periods between the BeginTime and EndTime. When I run this query in MySQL on a sample dataset, it returns a small number of rows, with each one being the min/max values for a portion of the overall period.
Under MS SQL Server 2008, SP3, I get the two following error messages: Column 'SensorData.StartTime' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause. Column 'SensorData.Offset' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
'Banquets - All Day' as revName, SUM(t.c_items_total) AS Banquet_Total, SUM(t.cover_count) as Total_Covers, -- (t.c_items_total) / (t.cover_count) as AvgPer_Cover--
[Code] ....
The output needs to be grouped by the t.c_items_total...I just need the avg per cover (person) / items_total.
I would like to be able to combine the functionality of IN and LIKE in a WHERE clause. Although the simple AdventureWorks2012 example below illustrates the concept with 3 search criteria, the real-world example I need to apply the concept to has a couple dozen. This returns 50 rows, but requires multiple OR ... LIKE functions:
SELECT DISTINCT c.Name FROM Sales.Store c WHERE c.Name LIKE '% sports %' OR c.Name LIKE '% exercise %' OR c.Name LIKE '%toy%'
What I would like to do is something like this, which doesn't work:
SELECT DISTINCT c.Name FROM Sales.Store c WHERE c.Name IN(LIKE '% sports %', LIKE '% exercise %', LIKE '%toy%')
I could load up a cursor and loop through it, but the syntax is more cumbersome than the multiple LIKE statements, not to mention most SQL programmers are horrified at the mention of the abominable word 'cursor' for performance reasons.
A while back, a "quirky update" method was proposed for lightning fast running totals based on the three-part MSSQL UPDATE's SET statement and tally tables. However, some claimed this was not 100% absolutely guaranteed behavior.
How does the new OVER clause compare in terms of performance ?
DECLARE @Tbl TABLE ( pk int not null primary key identity, N int ) INSERT INTO @Tbl (N) SELECT TOP 1000 1 FROM syscolumns a CROSS JOIN syscolumns b SELECT pk, SUM(pk) OVER (ORDER BY pk ) FROM @Tbl
I am creating a dynamic query where i am appending a where clause something like -
IF (@CurCaptureDate IS NOT NULL) SET @where_clause = @where_clause + CHAR(10) + 'AND CD.CaptureDate = ' + @CurCaptureDate
PS - CD.CaptureDate is datetime and @CurCaptureDate is also datetime
but when executing , it gives this error - Msg 241, Level 16, State 1, Line 169 Conversion failed when converting date and/or time from character string.
i am not able to use convert here with these quotes.
i tried this - SET @where_clause = @where_clause + CHAR(10) + 'AND CD.CaptureDate = ' + CONVERT(VARCHAR(25),@CurCaptureDate )
but it makes it to -
AND CD.CaptureDate = Jul 19 2014 12:00AM. I would need the date in quotes.