Search Results

Search found 1369 results on 55 pages for 'clause'.

Page 1/55 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • SQL join: where clause vs. on clause

    - by BCS
    After reading it, this is not a duplicate of Explicit vs Implicit SQL Joins. The answer may be related (or even the same) but the question is different. What is the difference and what should go in each? If I understand the theory correctly, the query optimizer should be able to use both interchangeably.

    Read the article

  • LINQ to XML : A query body must end with a select clause or a group clause

    - by Josh
    Can someone guide me on to repairing the error on this query : var objApps = from item in xDoc.Descendants("VHost") where(from x in item.Descendants("Application")) select new clsApplication { ConnectionsTotal = item.Element("ConnectionsTotal").Value }; It displays a compiler error "A query body must end with a select clause or a group clause". Where am I going wrong? Would appreciate any help.. Thanks. Edit : Here is my XML(haven't closed the tags here)...I need the connectioncount values inside the Application.. - <Server> <ConnectionsCurrent>67</ConnectionsCurrent> <ConnectionsTotal>1424182</ConnectionsTotal> <ConnectionsTotalAccepted>1385091</ConnectionsTotalAccepted> <ConnectionsTotalRejected>39091</ConnectionsTotalRejected> <MessagesInBytesRate>410455.0</MessagesInBytesRate> <MessagesOutBytesRate>540146.0</MessagesOutBytesRate> - <VHost> <Name>_defaultVHost_</Name> <TimeRunning>5129615.178</TimeRunning> <ConnectionsLimit>0</ConnectionsLimit> <ConnectionsCurrent>67</ConnectionsCurrent> <ConnectionsTotal>1424182</ConnectionsTotal> <ConnectionsTotalAccepted>1385091</ConnectionsTotalAccepted> <ConnectionsTotalRejected>39091</ConnectionsTotalRejected> <MessagesInBytesRate>410455.0</MessagesInBytesRate> <MessagesOutBytesRate>540146.0</MessagesOutBytesRate> - <Application> <Name>TestApp</Name> <Status>loaded</Status> <TimeRunning>411642.953</TimeRunning> <ConnectionsCurrent>11</ConnectionsCurrent> <ConnectionsTotal>43777</ConnectionsTotal> <ConnectionsTotalAccepted>43135</ConnectionsTotalAccepted> <ConnectionsTotalRejected>642</ConnectionsTotalRejected> <MessagesInBytesRate>27876.0</MessagesInBytesRate> <MessagesOutBytesRate>175053.0</MessagesOutBytesRate>

    Read the article

  • The overlooked OUTPUT clause

    - by steveh99999
    I often find myself applying ad-hoc data updates to production systems – usually running scripts written by other people. One of my favourite features of SQL syntax is the OUTPUT clause – I find this is rarely used, and I often wonder if this is due to a lack of awareness of this feature.. The OUTPUT clause was added to SQL Server in the SQL 2005 release – so has been around for quite a while now, yet I often see scripts like this… SELECT somevalue FROM sometable WHERE keyval = XXX UPDATE sometable SET somevalue = newvalue WHERE keyval = XXX -- now check the update has worked… SELECT somevalue FROM sometable WHERE keyval = XXX This can be rewritten to achieve the same end-result using the OUTPUT clause. UPDATE sometable SET somevalue = newvalue OUTPUT deleted.somevalue AS ‘old value’,              inserted.somevalue AS ‘new value’ WHERE keyval = XXX The Update statement with output clause also requires less IO - ie I've replaced three SQL Statements with one, using only a third of the IO.  If you are not aware of the power of the output clause – I recommend you look at the output clause in books online And finally here’s an example of the output produced using the Northwind database…  

    Read the article

  • Oracle SQL clause evaluation order

    - by jon.johnson
    In Oracle, which clause types get evaluated first? If I had the following ( pretend .... represent valid expressions and relation names ), what would the order of evaluation be? SELECT ... FROM ..... WHERE ........ GROUP BY ........... HAVING ............. ORDER BY ................ I am under the impression that the SELECT clause is evaluated last, but other than that I'm clueless.

    Read the article

  • Visual Web Developer, custom WHERE-clause for DataList, DataGrid

    - by m3n
    This question is not really related to programming but to using Visual Web Developer, but here goes: I'd like to use User.Identity.Name or any session variable in the WHERE-clause used by DataList (or other similar components), but I've tried the different options in the "ORDER BY..." pane to no avail. How do I stick that in there? Cheers

    Read the article

  • Difference b/w putting condition in JOIN clause versus WHERE clause

    - by user244953
    Suppose I have 3 tables. Sales Rep Rep Code First Name Last Name Phone Email Sales Team Orders Order Number Rep Code Customer Number Order Date Order Status Customer Customer Number Name Address Phone Number I want to get a detailed report of Sales for 2010. I would be doing a join. I am interested in knowing which of the following is more efficient and why ? SELECT O.OrderNum, R.Name, C.Name FROM Order O INNER JOIN Rep R ON O.RepCode = R.RepCode INNER JOIN Customer C ON O.CustomerNumber = C.CustomerNumber WHERE O.OrderDate >= '01/01/2010' OR SELECT O.OrderNum, R.Name, C.Name FROM Order O INNER JOIN Rep R ON (O.RepCode = R.RepCode AND O.OrderDate >= '01/01/2010') INNER JOIN Customer C ON O.CustomerNumber = C.CustomerNumber

    Read the article

  • Where clause in joins vs Where clause in Sub Query

    - by Kanavi
    DDL create table t ( id int Identity(1,1), nam varchar(100) ) create table t1 ( id int Identity(1,1), nam varchar(100) ) DML Insert into t( nam)values( 'a') Insert into t( nam)values( 'b') Insert into t( nam)values( 'c') Insert into t( nam)values( 'd') Insert into t( nam)values( 'e') Insert into t( nam)values( 'f') Insert into t1( nam)values( 'aa') Insert into t1( nam)values( 'bb') Insert into t1( nam)values( 'cc') Insert into t1( nam)values( 'dd') Insert into t1( nam)values( 'ee') Insert into t1( nam)values( 'ff') Query - 1 Select t.*, t1.* From t t Inner join t1 t1 on t.id = t1.id Where t.id = 1 Query 1 SQL profiler Result Reads = 56, Duration = 4 Query - 2 Select T1.*, K.* from ( Select id, nam from t Where id = 1 )K Inner Join t1 T1 on T1.id = K.id Query 2 SQL Profiler Results Reads = 262 and Duration = 2 You can also see my SQlFiddle Query - Which query should be used and why?

    Read the article

  • SQL where clause to work with Group by clause after performing a count()

    - by Matt
    Tried my usual references at w3schools and google. No luck I'm trying to produce the following results. QTY is a derived column | Position | QTY -------------------- 1 Clerk 2 2 Mgr 2 Here's what I'm not having luck with: SELECT Position, Count(position) AS 'QTY' FROM tblemployee Where ('QTY' != 1) GROUP BY Position I know that my Position is set up as varchar(255) Count produces a integer data and my where clasue is accurate so that leads me to believe that that Count() is jamming me up. Please throw up an example so I can reference later. Thanks for the help!

    Read the article

  • Linq where clause with multiple conditions and null check

    - by SocialAddict
    I'm trying to check if a date is not null in linq and if it isn't check its a past date. QuestionnaireRepo.FindAll(q => !q.ExpiredDate.HasValue || q.ExpiredDate >DateTime.Now).OrderByDescending(order => order.CreatedDate); I need the second check to only apply if the first is true. I am using a single repository pattern and FindAll accepted a where clause ANy ideas? There are lots of similar questions on here but not that give the answer, I'm very new to Linq as you may of guessed :) Edit: I get the results I require now but it will be checking the conditional on null values in some cases. Is this not a bad thing?

    Read the article

  • SQL: select rows with the same order as IN clause

    - by Andrea3000
    I know that this question has been asked several times and I've read all the answer but none of them seem to completely solve my problem. I'm switching from a mySQL database to a MS Access database with MS SQL. In both of the case I use a php script to connect to the database and perform SQL queries. I need to find a suitable replacement for a query I used to perform on mySQL. I want to: perform a first query and order records alphabetically based on one of the columns construct a list of IDs which reflects the previous alphabetical order perform a second query with the IN clause applied with the IDs' list and ordered by this list. In mySQL I used to perform the last query this way: SELECT name FROM users WHERE id IN ($name_ids) ORDER BY FIND_IN_SET(id,'$name_ids') Since FIND_IN_SET is available only in mySQL and CHARINDEX and PATINDEX are not available from my php script, how can I achieve this? I know that I could write something like: SELECT name FROM users WHERE id IN ($name_ids) ORDER BY CASE id WHEN ... THEN 1 WHEN ... THEN 2 WHEN ... THEN 3 WHEN ... THEN 4 END but you have to consider that: IDs' list has variable length and elements because it depends on the first query that list can easily contains thousands of elements Have you got any hint on this? Is there a way to programmatically construct the ORDER BY CASE ... WHEN ... statement? Is there a better approach since my list of IDs can be big?

    Read the article

  • Jquery query XML document where clause

    - by user578406
    I have an XML document that I want to search a specific date and get information for just that date. My XML looks like this: <month id="01"> <day id="1"> <eitem type="dayinfo"> <caption> <text lang="cy">f. 3 r.</text> <text lang="en">f. 3 r.</text> </caption> <ref href="link" id="3"/> <thumb href="link" id="3"/> </eitem> </day> <day id="7"> <eitem type="dayinfo"> <caption> <text lang="cy">f. 5 v.</text> <text lang="en">f. 5 v.</text> </caption> <ref href="link" id="4"/> <thumb href="link" id="4"/> </eitem> </day> <day id="28"> <eitem type="dayinfo2"> <caption id="1"> <text lang="cy">test</text> <text lang="en">test2</text> </caption> <ref href="link" id="1"/> <thumb href="link" id="1"/> </eitem> </day> <day id="28"> <eitem type="dayinfo"> <caption> <text lang="cy">f. 14 v.</text> <text lang="en">f. 14 v.</text> </caption> <ref href="link" id="20"/> <thumb href="link" id="20"/> </eitem> </day> </month> My Jquery looks like this: $(xml).find('month[id=01]').each(function() { $(xml).find("day").each(function() { var day = $(this).attr('id'); alert(day); }); }); In the XML example above I only shown one month, however there are many more. In my JQuery I've tried to do 'Where month = 1' and get all the days info for that month, however that JQuery brings back days for every month. How do I do a where clause with JQuery/JavaScript on a XML document? thanks.

    Read the article

  • C#/.NET Little Wonders: Constraining Generics with Where Clause

    - by James Michael Hare
    Back when I was primarily a C++ developer, I loved C++ templates.  The power of writing very reusable generic classes brought the art of programming to a brand new level.  Unfortunately, when .NET 1.0 came about, they didn’t have a template equivalent.  With .NET 2.0 however, we finally got generics, which once again let us spread our wings and program more generically in the world of .NET However, C# generics behave in some ways very differently from their C++ template cousins.  There is a handy clause, however, that helps you navigate these waters to make your generics more powerful. The Problem – C# Assumes Lowest Common Denominator In C++, you can create a template and do nearly anything syntactically possible on the template parameter, and C++ will not check if the method/fields/operations invoked are valid until you declare a realization of the type.  Let me illustrate with a C++ example: 1: // compiles fine, C++ makes no assumptions as to T 2: template <typename T> 3: class ReverseComparer 4: { 5: public: 6: int Compare(const T& lhs, const T& rhs) 7: { 8: return rhs.CompareTo(lhs); 9: } 10: }; Notice that we are invoking a method CompareTo() off of template type T.  Because we don’t know at this point what type T is, C++ makes no assumptions and there are no errors. C++ tends to take the path of not checking the template type usage until the method is actually invoked with a specific type, which differs from the behavior of C#: 1: // this will NOT compile! C# assumes lowest common denominator. 2: public class ReverseComparer<T> 3: { 4: public int Compare(T lhs, T rhs) 5: { 6: return lhs.CompareTo(rhs); 7: } 8: } So why does C# give us a compiler error even when we don’t yet know what type T is?  This is because C# took a different path in how they made generics.  Unless you specify otherwise, for the purposes of the code inside the generic method, T is basically treated like an object (notice I didn’t say T is an object). That means that any operations, fields, methods, properties, etc that you attempt to use of type T must be available at the lowest common denominator type: object.  Now, while object has the broadest applicability, it also has the fewest specific.  So how do we allow our generic type placeholder to do things more than just what object can do? Solution: Constraint the Type With Where Clause So how do we get around this in C#?  The answer is to constrain the generic type placeholder with the where clause.  Basically, the where clause allows you to specify additional constraints on what the actual type used to fill the generic type placeholder must support. You might think that narrowing the scope of a generic means a weaker generic.  In reality, though it limits the number of types that can be used with the generic, it also gives the generic more power to deal with those types.  In effect these constraints says that if the type meets the given constraint, you can perform the activities that pertain to that constraint with the generic placeholders. Constraining Generic Type to Interface or Superclass One of the handiest where clause constraints is the ability to specify the type generic type must implement a certain interface or be inherited from a certain base class. For example, you can’t call CompareTo() in our first C# generic without constraints, but if we constrain T to IComparable<T>, we can: 1: public class ReverseComparer<T> 2: where T : IComparable<T> 3: { 4: public int Compare(T lhs, T rhs) 5: { 6: return lhs.CompareTo(rhs); 7: } 8: } Now that we’ve constrained T to an implementation of IComparable<T>, this means that our variables of generic type T may now call any members specified in IComparable<T> as well.  This means that the call to CompareTo() is now legal. If you constrain your type, also, you will get compiler warnings if you attempt to use a type that doesn’t meet the constraint.  This is much better than the syntax error you would get within C++ template code itself when you used a type not supported by a C++ template. Constraining Generic Type to Only Reference Types Sometimes, you want to assign an instance of a generic type to null, but you can’t do this without constraints, because you have no guarantee that the type used to realize the generic is not a value type, where null is meaningless. Well, we can fix this by specifying the class constraint in the where clause.  By declaring that a generic type must be a class, we are saying that it is a reference type, and this allows us to assign null to instances of that type: 1: public static class ObjectExtensions 2: { 3: public static TOut Maybe<TIn, TOut>(this TIn value, Func<TIn, TOut> accessor) 4: where TOut : class 5: where TIn : class 6: { 7: return (value != null) ? accessor(value) : null; 8: } 9: } In the example above, we want to be able to access a property off of a reference, and if that reference is null, pass the null on down the line.  To do this, both the input type and the output type must be reference types (yes, nullable value types could also be considered applicable at a logical level, but there’s not a direct constraint for those). Constraining Generic Type to only Value Types Similarly to constraining a generic type to be a reference type, you can also constrain a generic type to be a value type.  To do this you use the struct constraint which specifies that the generic type must be a value type (primitive, struct, enum, etc). Consider the following method, that will convert anything that is IConvertible (int, double, string, etc) to the value type you specify, or null if the instance is null. 1: public static T? ConvertToNullable<T>(IConvertible value) 2: where T : struct 3: { 4: T? result = null; 5:  6: if (value != null) 7: { 8: result = (T)Convert.ChangeType(value, typeof(T)); 9: } 10:  11: return result; 12: } Because T was constrained to be a value type, we can use T? (System.Nullable<T>) where we could not do this if T was a reference type. Constraining Generic Type to Require Default Constructor You can also constrain a type to require existence of a default constructor.  Because by default C# doesn’t know what constructors a generic type placeholder does or does not have available, it can’t typically allow you to call one.  That said, if you give it the new() constraint, it will mean that the type used to realize the generic type must have a default (no argument) constructor. Let’s assume you have a generic adapter class that, given some mappings, will adapt an item from type TFrom to type TTo.  Because it must create a new instance of type TTo in the process, we need to specify that TTo has a default constructor: 1: // Given a set of Action<TFrom,TTo> mappings will map TFrom to TTo 2: public class Adapter<TFrom, TTo> : IEnumerable<Action<TFrom, TTo>> 3: where TTo : class, new() 4: { 5: // The list of translations from TFrom to TTo 6: public List<Action<TFrom, TTo>> Translations { get; private set; } 7:  8: // Construct with empty translation and reverse translation sets. 9: public Adapter() 10: { 11: // did this instead of auto-properties to allow simple use of initializers 12: Translations = new List<Action<TFrom, TTo>>(); 13: } 14:  15: // Add a translator to the collection, useful for initializer list 16: public void Add(Action<TFrom, TTo> translation) 17: { 18: Translations.Add(translation); 19: } 20:  21: // Add a translator that first checks a predicate to determine if the translation 22: // should be performed, then translates if the predicate returns true 23: public void Add(Predicate<TFrom> conditional, Action<TFrom, TTo> translation) 24: { 25: Translations.Add((from, to) => 26: { 27: if (conditional(from)) 28: { 29: translation(from, to); 30: } 31: }); 32: } 33:  34: // Translates an object forward from TFrom object to TTo object. 35: public TTo Adapt(TFrom sourceObject) 36: { 37: var resultObject = new TTo(); 38:  39: // Process each translation 40: Translations.ForEach(t => t(sourceObject, resultObject)); 41:  42: return resultObject; 43: } 44:  45: // Returns an enumerator that iterates through the collection. 46: public IEnumerator<Action<TFrom, TTo>> GetEnumerator() 47: { 48: return Translations.GetEnumerator(); 49: } 50:  51: // Returns an enumerator that iterates through a collection. 52: IEnumerator IEnumerable.GetEnumerator() 53: { 54: return GetEnumerator(); 55: } 56: } Notice, however, you can’t specify any other constructor, you can only specify that the type has a default (no argument) constructor. Summary The where clause is an excellent tool that gives your .NET generics even more power to perform tasks higher than just the base "object level" behavior.  There are a few things you cannot specify with constraints (currently) though: Cannot specify the generic type must be an enum. Cannot specify the generic type must have a certain property or method without specifying a base class or interface – that is, you can’t say that the generic must have a Start() method. Cannot specify that the generic type allows arithmetic operations. Cannot specify that the generic type requires a specific non-default constructor. In addition, you cannot overload a template definition with different, opposing constraints.  For example you can’t define a Adapter<T> where T : struct and Adapter<T> where T : class.  Hopefully, in the future we will get some of these things to make the where clause even more useful, but until then what we have is extremely valuable in making our generics more user friendly and more powerful!   Technorati Tags: C#,.NET,Little Wonders,BlackRabbitCoder,where,generics

    Read the article

  • Dynamic where clause using Linq to SQL in a join query in a MVC application

    - by jhoefnagels
    Dear .Net Linq experts, I am looking for a way to query for products in a catalog using filters on properties which have been assigned to the product based on the category to which the product belongs. So I have the following entities involved: Products -Id -CategoryId Categories [Id] Properties [Id, CategoryId] PropertyValues [Id, PropertyId] ProductProperties [ProductId, PropertyValueId] When I ad a product to the catalog, multiple ProductProperties will be added based on the category and I would like to be able to filter all products from a category by selecting values for one or more properties. I will gather all filters, which I will hold in a list, by reading the URL. Now it is time to actually get the products based on multiple properties and I have been trying to find the right strategy but untill now it does not really work. Is there a way to make this work without writing SQL? I was trying something like this: productsInCategory = ProductRepository.Where(p => p.Category.Name == category); foreach (PropertyFilter pf in filterList) { productsInCategory = (from product in productsInCategory join pp in ProductPropertyRepository on product.Id equals pp.ProductId where pp.PropertyValueId == pf.ValueId select product); }

    Read the article

  • linq where clause not in select statement

    - by Annie
    Can someone help me to convert from SQL Query to LINQ VB.NET: select rls.* from Roles rls(nolock) where rls.id not in ( select r.ID from usersRole ur (nolock) inner join Roles r(nolock) on ur.RoleID = r.ID where user_id = 'NY1772') Thanks

    Read the article

  • DELETE from two tables with one OUTPUT clause?

    - by lance
    This deletes the document from the Document table and outputs information about the deleted document into the FinishedDocument table. DELETE FROM Document OUTPUT Deleted.DocumentId , Deleted.DocumentDescription INTO FinishedDocument WHERE DocumentId = @DocumentId I need to delete the document not just from the Document table, but also from the DocumentBackup table. Meanwhile, I need to maintain insertion into FinishedDocument. Is all of this possible with only one statement? If not, is a second DELETE (against DocumentBackup), with all of it wrapped in a transaction, the way to go?

    Read the article

  • how to add WHERE clause to Query on android

    - by Brian
    I would like to limit the results to those whose KEY_HOMEID is equal to journalId. I've been on this for a couple days any help would be appreciated. public Cursor fetchAllNotes(String journalId) { return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_HEIGHT, KEY_BODY, KEY_HOMEID},"FROM DATABASE_TABLE WHERE KEY_HOMEID = journalId",null, null, null, null,null); }

    Read the article

  • SQL Server - In clause with a declared variable

    - by Melursus
    Let say I got the following : DECLARE @ExcludedList VARCHAR(MAX) SET @ExcludedList = 3 + ', ' + 4 + ' ,' + '22' SELECT * FROM A WHERE Id NOT IN (@ExcludedList) Error : Conversion failed when converting the varchar value ', ' to data type int. I understand why the error is there but I don't know how to solve it...

    Read the article

  • MYSQL and the LIMIT clause

    - by Lizard
    I was wondering if adding a LIMIT 1 to a query would speed up the processing? For example... I have a query that will most of the time return 1 result, but will occasionaly return 10's, 100's or even 1000's of records. But I will only ever want the first record. Would the limit 1 speed things up or make no difference? I know I could use GROUP BY to return 1 result but that would just add more computation. Any thoughts gladly accepted! Thanks

    Read the article

  • WordPress: Using a Where Clause With A Custom Field

    - by Steve Wilkison
    I have a bunch of events that are listed on a particular page. Each event is a post. I need them to display in the order in which they occur, NOT the order of the posting date. So, I've created a custom field called TheDate and enter in the date in this format for each one: 20110306. Then, I wrote my query like this: query_posts( array ( 'cat' => '4', 'posts_per_page' => -1, 'orderby' => 'meta_value_num', 'meta_key' => 'TheDate', 'order' => 'ASC' ) ); Works perfectly and displays the events in the correct order. However, I also want it to ONLY display dates from today onward. I don't want it to display dates which have passed. It seems the way to do this is with a "filter." I tried this, but it doesn't work. $todaysdate = date('Ymd'); query_posts( array ( 'cat' => '4', 'posts_per_page' => -1, 'orderby' => 'meta_value_num', 'meta_key' => 'TheDate', 'order' => 'ASC' ) ); function filter_where( $where = '' ) { $where .= "meta_value_num >= $todaysdate"; return $where; } add_filter( 'posts_where', 'filter_where' ); I figure it's just a matter of where I'm using this filter, I probably have it in the wrong place. Or maybe the filter itself is bad. Any help or guidance would be greatly appreciated. Thanks!

    Read the article

  • Using an IN clause in Vb.net to save something to the database using SQL

    - by Rob
    I have a textbox and a button on a form. I wish to run a query (in Vb.Net) that will produce a query with the IN Values. Below is an example of my code myConnection = New SqlConnection("Data Source=sqldb\;Initial Catalog=Rec;Integrated Security=True") myConnection.Open() myCommand = New SqlCommand("UPDATE dbo.Recordings SET Status = 0 where RecID in ('" & txtRecID.Text & "') ", myConnection) ra = myCommand.ExecuteNonQuery() myConnection.Close() MsgBox("Done!", _ MsgBoxStyle.Information, "Done") When I enter a single value it works but when I enter values with commas it throws an error: "Conversion failed when converting the varchar value '1234,4567' to data type int." Could someone please help me to solve this or if there is an alternative way? Many Thanks

    Read the article

  • SQL SERVER – Introduction to Rollup Clause

    - by pinaldave
    In this article we will go over basic understanding of Rollup clause in SQL Server. ROLLUP clause is used to do aggregate operation on multiple levels in hierarchy. Let us understand how it works by using an example. Consider a table with the following structure and data: CREATE TABLE tblPopulation ( Country VARCHAR(100), [State] VARCHAR(100), City VARCHAR(100), [Population (in Millions)] INT ) GO INSERT INTO tblPopulation VALUES('India', 'Delhi','East Delhi',9 [...]

    Read the article

  • SQL SERVER – Use ROLL UP Clause instead of COMPUTE BY

    - by pinaldave
    Note: This upgrade was test performed on development server with using bits of SQL Server 2012 RC0 (which was available at in public) when this test was performed. However, SQL Server RTM (GA on April 1) is expected to behave similarly. I recently observed an upgrade from SQL Server 2005 to SQL Server 2012 with compatibility keeping at SQL Server 2012 (110). After upgrading the system and testing the various modules of the application, we quickly observed that few of the reports were not working. They were throwing error. When looked at carefully I noticed that it was using COMPUTE BY clause, which is deprecated in SQL Server 2012. COMPUTE BY clause is replaced by ROLL UP clause in SQL Server 2012. However there is no direct replacement of the code, user have to re-write quite a few things when using ROLL UP instead of COMPUTE BY. The primary reason is that how each of them returns results. In original code COMPUTE BY was resulting lots of result set but ROLL UP. Here is the example of the similar code of ROLL UP and COMPUTE BY. I personally find the ROLL UP much easier than COMPUTE BY as it returns all the results in single resultset unlike the other one. Here is the quick code which I wrote to demonstrate the said behavior. CREATE TABLE tblPopulation ( Country VARCHAR(100), [State] VARCHAR(100), City VARCHAR(100), [Population (in Millions)] INT ) GO INSERT INTO tblPopulation VALUES('India', 'Delhi','East Delhi',9 ) INSERT INTO tblPopulation VALUES('India', 'Delhi','South Delhi',8 ) INSERT INTO tblPopulation VALUES('India', 'Delhi','North Delhi',5.5) INSERT INTO tblPopulation VALUES('India', 'Delhi','West Delhi',7.5) INSERT INTO tblPopulation VALUES('India', 'Karnataka','Bangalore',9.5) INSERT INTO tblPopulation VALUES('India', 'Karnataka','Belur',2.5) INSERT INTO tblPopulation VALUES('India', 'Karnataka','Manipal',1.5) INSERT INTO tblPopulation VALUES('India', 'Maharastra','Mumbai',30) INSERT INTO tblPopulation VALUES('India', 'Maharastra','Pune',20) INSERT INTO tblPopulation VALUES('India', 'Maharastra','Nagpur',11 ) INSERT INTO tblPopulation VALUES('India', 'Maharastra','Nashik',6.5) GO SELECT Country,[State],City, SUM ([Population (in Millions)]) AS [Population (in Millions)] FROM tblPopulation GROUP BY Country,[State],City WITH ROLLUP GO SELECT Country,[State],City, [Population (in Millions)] FROM tblPopulation ORDER BY Country,[State],City COMPUTE SUM([Population (in Millions)]) BY Country,[State]--,City GO After writing this blog post I continuously feel that there should be some better way to do the same task. Is there any easier way to replace COMPUTE BY? Reference: Pinal Dave (http://blog.sqlauthority.com) Filed under: PostADay, SQL, SQL Authority, SQL Query, SQL Server, SQL Tips and Tricks, T SQL, Technology

    Read the article

  • What's the difference between the code inside a finally clause and the code located after catch clause?

    - by facebook-100005613813158
    My java code is just like below: public void check()throws MissingParamException{ ...... } public static void main(){ PrintWriter out = response.getWriter(); try { check(); } catch (MissingParamException e) { // TODO Auto-generated catch block out.println("message:"+e.getMessage()); e.printStackTrace(); out.close(); }finally{ out.close(); } //out.close(); } Then, my confusion is: what the difference if I put out.close() in a finally code block or if I just remove finally code block and put out.close() behind catch clause (which has been commented in the code). I know that in both ways, the out.close() will be executed because I know that whether the exception happened, the code behind the catch clause will always be executed.

    Read the article

  • The Exceptional EXCEPT clause

    - by steveh99999
    Ok, I exaggerate, but it can be useful… I came across some ‘poorly-written’ stored procedures on a SQL server recently, that were using sp_xml_preparedocument. Unfortunately these procs were  not properly removing the memory allocated to XML structures – ie they were not subsequently calling sp_xml_removedocument… I needed a quick way of identifying on the server how many stored procedures this affected.. Here’s what I used.. EXEC sp_msforeachdb 'USE ? SELECT DB_NAME(),OBJECT_NAME(s1.id) FROM syscomments s1 WHERE [text] LIKE ''%sp_xml_preparedocument%'' EXCEPT SELECT DB_NAME(),OBJECT_NAME(s2.id) FROM syscomments s2 WHERE [text] LIKE ''%sp_xml_removedocument%'' ‘ There’s three nice features about the code above… 1. It uses sp_msforeachdb. There’s a nice blog on this statement here 2. It uses the EXCEPT clause.  So in the above query I get all the procedures which include the sp_xml_preparedocument string, but by using the EXCEPT clause I remove all the procedures which contain sp_xml_removedocument.  Read more about EXCEPT here 3. It can be used to quickly identify incorrect usage of sp_xml_preparedocument. Read more about this here The above query isn’t perfect – I’m not properly parsing the SQL text to ignore comments for example - but for the quick analysis I needed to perform, it was just the job…

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >