w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
FirstOrDefault returning Unexpected Value
The default value for integer is 0. FirstOrDefault return the first occurrency or default value, in your case, you a re using int, so, it is 0. If you want a exception when do not have a item, try using First(x => x > 5).

Categories : C#

How to use RETURNING clause in PostgreSQL?
You can also explicitly read the current value of the sequence and return that: INSERT INTO alarms (al_id, al_descr) VALUES (DEFAULT, 'description') RETURNING currval('allarmi_al_id_seq') AS al_id; Note that the currval function returns the most recently obtained value in this session, so there are no concurrency issues (unless you have a trigger that causes the sequence to be incremented).

Categories : SQL

MS SQL Where Like Clause Not Returning Data
The most likely reason is that there is some unseen character after the 08. One way this could occur is if the field is defined as a char; it would then be padded with spaces. One way to see if there are any such values is to append characters to delimit the value: select '|'+char_data+'|' . . . You have another problem in your query. You are using varchar without a length. Bad, bad, bad. In fact, the convert doesn't seem to be needed at all. You can just do: substring(char_data, 9, 16) LIKE '%BrightSide08' But this is equivalent to: left(char_data, 25) LIKE '%BrightSide08' Or, because you are looking for values at the end of the field: right(char_data, 12) = 'BrightSide08'

Categories : Sql Server

SQL query not returning data from where clause
Try this: SELECT * FROM #PreModuleAllData WITH(NOLOCK) WHERE (@Country = 'DEFAULT' OR @Country = '' OR ([Language] = @Country )) AND (@UserType = 'DEFAULT' OR @UserType = '' OR ([UserType] = @UserType )) AND (@Group = 'DEFAULT' OR @Group = '' OR ([Company] = @Group )) AND (@CodeUsage = 'DEFAULT' OR @CodeUsage = '' OR ([User Code]= @CodeUsage ))

Categories : SQL

Case subquery returning too many rows within where clause
SELECT `Job ID` FROM jobs WHERE `Building ID` = '1' and case when `Appointment Date` IS NOT NULL then `Appointment Date` = '2013-10-10' else `Backup Date` = '2013-10-10' end

Categories : Mysql

Linq query where clause returning null
You don't need to cast to string in where clause also you need to compare it against Value like where exp.Element("Posted_Status").Value == "Ready" Try: var expiration = from exp in main.Elements("Network") where exp.Element("Posted_Status").Value.Equals("Ready", StringComparison.CurrentCulture) select new { Timed_On = exp.Element("Timed_On").Value, Timed_Off = exp.Element("Timed_Off").Value, }; For Ouput: foreach (var item in expiration) { Console.WriteLine("Timed_On: {0} Timed_Off: {1}", item.Timed_On, item.Timed_Off ); } (Its better if you parse the values to a propert DateTime object)

Categories : C#

Query returning syntax error in FROM clause
You have to remove tables from from statement if you want to use join syntax SELECT tableA.name, tableB.name, tableB.address, tableC.name FROM tableA INNER JOIN tableB ON tableA.id = tableB.A_ID INNER JOIN tableC ON tableA.id = tableC.A_ID WHERE tableA.name = 'something' I suggest you to use aliases, the code could be more readable: SELECT A.name, B.name, B.address, C.name FROM tableA A INNER JOIN tableB B ON A.id = B.A_ID INNER JOIN tableC C ON A.id = C.A_ID WHERE A.name = 'something'

Categories : C#

Return ID of last inserted row in PostgreSQL with RETURNING clause
You're missing the variable declaration, the INTO clause and the final RETURN: CREATE OR REPLACE FUNCTION create_new_order(....) RETURNS integer AS $BODY$ DECLARE var_ident int; BEGIN PERFORM add_points_to_usage(client_id_p, date_in_p, total_points_p); INSERT INTO orders (...) VALUES (...) RETURNING ident INTO var_ident; RETURN var_ident; END; $BODY$ LANGUAGE plpgsql;

Categories : Postgresql

LINQ-to-SQL query not returning row when where clause compares against NULL value
The first query doesn't behave as expected, because it is translated into SQL that is equivalent to the following: select * from RoleTable where Role != 'Admin' Now, in SQL NULL != 'Admin' is not TRUE (nor is it FALSE - it is undefined). That's one of the many cases where the abstraction that LINQ to SQL provides is leaky and you still need to know SQL. BTW: Your second query is also incorrect, it will select only those rows that are null. It wouldn't select a row with the role 'User'. The correct query would look like this: List<types> t2 = (from a in datacontext.RoleTable where a.Role != "Admin" || a.Role == null select a).ToList();

Categories : C#

DYNAMIC SQL RETURNING clause giving error in Oracle 10g
Your returning clause is attempting to return columns empname and deptid, when the columns in the table are emp_name and dept_id. It isn't the local variables names that are the problem, or mentioned in the error message. So you need: ... RETURNING emp_id, dept_id, age, sex INTO ... I'm not sure why you've dropped the underscores in your local variable names; it might be less confusing if you had v_emp_id, v_emp_name and v_dept_id. Of course this doesn't need to be done with dynamic SQL anyway, but I assume you're experimenting.

Categories : Oracle

LINQ Subquery in Where Clause returning error in LINQPad
It got resolved. Correct navigation route for the lines in error was: .Where(e => innerquery.Any(a => a.com_id == e.customer.application.com_id)) // exception at this line .Where(e => innerquery.Any(a => a.fnd_id == e.customer.application.fnd_id)) The error was due to e.advice.application

Categories : C#

Is the use of the RETURNING INTO clause faster than a separate SELECT statement?
Just as I thought: Often, applications need information about the row affected by a SQL operation, for example, to generate a report or take a subsequent action. The INSERT, UPDATE, and DELETE statements can include a RETURNING clause, which returns column values from the affected row into PL/SQL variables or host variables. This eliminates the need to SELECT the row after an insert or update, or before a delete. As a result, fewer network round trips, less server CPU time, fewer cursors, and less server memory are required. Taken from Oracle docs here

Categories : Oracle

FirstOrDefault Behavior with Int and Int?
Why don't I get a compile-time error (or at least a warning) when, for my first example, I use a Nullable int rather than a regular int then? If I understand correctly, using a int? when performing my first query will never result in a value of null. Your understanding is correct. However, the compiler does not interfere with your desire to declare variable a as nullable, because it is a "widening" conversion: even though the assignment from the LINQ query would never return a null, you may have other use for the same variable down below: int? a = (from x in list where (x == "hi") select x.Length).FirstOrDefault(); // Do something with `a`, which will not be null ... a = null; if (someCondition) { a = someNotNullValue(); } // Here, a may or may not be null ...

Categories : C#

How to use FirstOrDefault for two primary keys
Use the && operator in your lambda. var product = db.TMP_HELLO .FirstOrDefault<TMP_HELLO>( instrmnt => instrmnt.a == good.a && instrmnt.b == good.b);

Categories : C#

Unable to use FirstOrDefault on SqlParameterCollection
The reason you can't use FirstOrDefault is that SqlParameterCollection does not implement IEnumerable<SqlParameter> (on which the LINQ expressions are defined). The intended method of checking for a parameter is to use Contains if (cp.Contains("@ReturnValue")) If you really want to use LINQ operators, you can use Cast: cp.Cast<SqlParameter>() .FirstOrDefault(p => p.ParameterName == "@ReturnValue")

Categories : C#

Why the "FirstOrDefault()" is not required in the rasor code?
You have to add FirstOrDefault because your model is IEnumerable. So in order to get an instance you have to get one element from the IEnumerable thus, FirstOrDefault This presents a problem though, for if the model is null, the page will throw a runtime error when trying to access that property Col1. In the table, you are iterating over the items in the model therefore you won't need to do FirstOrDefault I would recommend creating a model that has a property that is the instance that you're looking to bind to. Example: public class MyViewModel { public MyModel MyModel { get; set; } public IEnumerable<MyModel> MyModels { get;set; } } Then: @model MyNameSpace.MyViewModel <div class="editor-field"> @Html.EditorFor(m => m.MyModel.Col1) @Html.V

Categories : Asp Net

NullReferenceException when using Group.FirstOrDefault with Value Type
When you pass a expression to FirstOrDefault your telling it select the first item that matches the expression (much like a Where clause but for the first object to match the clause). If you changed your statement to the following is it ok? Dim charges As List(Of IndividualCharge) = (From t In totals Group t By t.InvId Into Group Select New IndividualCharge With { .VatRate = Group.FirstOrDefault().VatRate }).ToList() If you wanted to get the first value that isn't zero something along these lines should do? Dim charges As List(Of IndividualCharge) = (From t In totals Group t By t.InvId Into Group Select New IndividualCharge Wit

Categories : Dotnet

c# Linq to Objects - FirstOrDefault performance
You should be able to speed it up by rewriting it as saldoPrivatiefKlantVerdeelsleutel.AfrekenPeriode.SaldoPrivatiefKlantVerdeelsleutelCollection .Where(s => (boeking == null || (s.SaldoVerdeelsleutel != null && (s.SaldoVerdeelsleutel.GebouwVerdeelSleutel.ID == boeking.SaldoGebouwRekeningVerdeling.SaldoGebouwRekening.SaldoVerdeelsleutel.GebouwVerdeelSleutel.ID))) && s.PrivatiefKlant.ID == privatiefKlant) .FirstOrDefault() See Why is LINQ .Where(predicate).First() faster than .First(predicate)? for why this is faster.

Categories : C#

linq Firstordefault check for default value
You wouldn't need to perform that equals check because your query only returns objects where the contantName is Stackoverflow. When you use FirstOrDefault it returns null if no objects were found so you can do if(contact == null) do something You know it's a reference type if Contact is a class so it's default value would be null. You can, however, check it's the default type of any object (reference of value) by using default. if(contact == default(Contact)) do something As mentioned in the comments, you can possibly make your code more efficient by using the overload of FirstOrDefault that takes a predicate. FirstOrDefault(m => m.contactName == "Stackoverflow") You can also change the default value returned if your program needs to work with something other than a nu

Categories : C#

"Unable to create a constant value of type 'User'" when using FirstOrDefault?
I think you've actually found a bug in Entity Framework. I'm envious! (EDIT: It looks like this bug has been fixed in EF 6.0.0-rc1) Here's why I think it's a bug: the machinery which is translating the expression predicate is definitely misbehaving for FirstOrDefault in a way that does not occur with Where. I can repro your issue against a similar schema with these contrived queries: // works var target = _context.Orders.Where (o => _context.Users.FirstOrDefault() != null).FirstOrDefault (); // Exception: Unable to create a constant value... target = _context.Orders.FirstOrDefault (o => _context.Users.FirstOrDefault() != null); Not only does it throw an exception, but observing the SQL in LINQPad you can see that an effective SELECT * FROM Users query is being issued right befo

Categories : Misc

Select FirstOrDefault Value Bind to Gridview Window Form C#
try with below var query = (from b in doc.WireLine_Movements where b.CustomerInvoiceNo.Contains(txtCustomerInvoiceNo.Text.Trim()) orderby b.ID descending select new { b.AssetCode, b.CustomerInvoiceNo, b.CurrentLocation, b.FromLocation}).Take(1).ToList(); You can't Bind one item to grid view. create list from the item and set it as datasourse

Categories : C#

Loop through Dictionary to find dataType if FirstOrDefault is Null
So, if you start by getting only your keys, and then pull the first non-null value for each key, it should simplify your logic (though it may be a bit more process intensive): if ( source != null ) { var keys = ( from d in source from k in d.Keys select k ).Distinct(); foreach ( var key in keys) { //...some logic to try and find if the key.Key Value in question has any legitimate value other than null to set the DataType to var thisKey = key; var valueNotNull = source.FirstOrDefault( dictionary => dictionary[thisKey] != null ); var colType = valueNotNull != null ? valueNotNull[thisKey].GetType() : typeof( string ); dt.Columns.Add( new DataColum

Categories : C#

SQL:in clause with query taking too long compared to in clause with actual data
Actually, MySQL execute the inner query at the end, it scans every indexes before. MySQL rewrites the subquery in order to make the inner query fully dependent of the outer one. For exemple, it select * from student (depend of your database, but could return many results), then apply the inner query user_id=4 to the previous result. The dev team are working on this problem and it should be "solved" in the 6.0 http://dev.mysql.com/doc/refman/5.5/en/optimizing-subqueries.html EDIT: In your case, you should use a JOIN method.

Categories : Mysql

unequal columns in two different select clause used union clause
Hopefully, I have understood you. If you wish to extract data from two tables, they dont need to have identical numbers of columns, but they DO need to have something in common. The generic sytnax would be: SELECT table1.col1, table2.col1 FROM table1 LEFT JOIN table2 ON table1.col3=table2.col3 WHERE {where conditions} What is important here is that there is a linking bit of data - often a usernumber that is common to both tables and means the same thing in both tables.

Categories : Mysql

Join Subquery in FROM clause aliased in WHERE clause
Try something like : SELECT MainTable.ID,MainTable.DETAILS,MainTable.ENTRYDATE,ISNULL(MainTable.LastBalance, 0) + ( SUM(subMainTable.VAL)) AS Balance FROM ( SELECT MainTable.* FROM tempData MainTable LEFT JOIN FinanceTable FinTable ON (MainTable.ID = FinTable.accId AND MainTable.TRANS_ID = FinTable.txnID ) WHERE (FinTable.accId IS NULL AND FinTable.txnID IS NULL ) ) AS MainTable left outer join ( SELECT TRANS_ID ,ID , SUM(VAL) FROM tempData subMainTable LEFT OUTER JOIN FinanceTable f ON subMainTable.ID = f.accId AND subMainTable.TRANS_ID = f.txnID WHERE f.txnID IS NULL ) as subMainTable on subMainTable.TRANS_ID <= MainTable.TRANS_ID AND subMainTable.ID = MainTable.ID group by MainTable.ID,MainTable.DETAILS,MainTab

Categories : SQL

MySQL index in between where clause and order by clause
Your key problem is that over 950k rows your status column has up to 4 distinct values. On a BTREE index, this will be a real pain to process. Some more effective indexes to use for the 3 queries mentioned are probably the following INDEX forQuery1 ( field_1 , status , rank ) USING BTREE, INDEX forQuery2 ( field_2 , status , rank ) USING BTREE, INDEX forQuery3 ( field_5 , status , rank ) USING BTREE, You'll find that the second query especially should benefit however you're still going to have the issue where the variance of the data is very low for the size of dataset and most likely MySQL will fall back to a table scan though your EXPLAIN will probably show the LIMIT to lessen the effect of that. The indexes mentioned should be suitable for determining which rows to return though.

Categories : Mysql

TSQL OVER CLAUSE That has no partition by has Order By clause
First one is not working for me (returning Msg 8120 Column 'Salaries.employeeID' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause), until I add group by employeeID: SELECT employeeID as ID, RANK() OVER (ORDER BY AVG (Salary) DESC) AS Value FROM Salaries GROUP BY employeeID Perhaps, for better understanding, it can be rewritten equivalently as: ;with cte as ( SELECT employeeID, AVG (Salary) as AvgSalary FROM Salaries GROUP BY employeeID ) select employeeID as ID , RANK() OVER (ORDER BY AvgSalary DESC) as Value --, AvgSalary from cte In this case, average salary by employee is calculated in the CTE, and then query is extended with ranking column Value. Adding partition by employeeID to over cl

Categories : Sql Server

Improving a LIKE clause through static clause elements
You can use EXPLAIN to know which query is faster. As a general concept it is better to have static queries than LIKE queries. So it gets faster if you add some. But only if it actually reduces the rows for the LIKE and the static query uses and index. The principle is that a LIKE style query (together with other queries that have to scan through the content of the field) is expensive. (see the cost column in the EXPLAIN) So, if you reduce the amount of rows that need to be treated for a LIKE the query gets faster. What exactly makes what query fast under what circumstances is hard to answer generally. You should ask precise questions to them including a description of your concrete situation (DBMS, table model, indexes, amount of data, result of an EXPLAIN call, etc.) to get working a

Categories : Mysql

Insert command with where clause and like clause
WHERE only applies to SELECT, UPDATE and DELETE. An INSERT creates a new record, using WHERE doesn't make any sense if there's nothing yet.

Categories : SQL

Oracle Query is returning value when setting value to it, but not returning value when passing date value
Since you're already forcing the date format, you can use the following query instead: SELECT INCIDENT_ID FROM INC_SM1 I WHERE I.CLOSE_TIME >= START_DATE AND I.CLOSE_TIME < END_DATE

Categories : Oracle

Python - Chaining methods: returning `self` vs returning a new cloned object
Django does this so that the base query can be kept around and reused, without inheriting changes from a future "child" query, like your exclude() on your filter(). I'm guessing somebody tried storing queries for later, and realized that didn't work well without copying. I cloned the django repo and did a quick git log on django/db/models/query.py, searching for the phrase clone. The patch that introduces this change is here: https://github.com/django/django/commit/d4a3a4b

Categories : Python

JavaScript, stringify, replacer - returning undefined vs. returning nothing
If you don't provide an explicit return, the return value is undefined. Your second function always returns undefined, in other words. Because the function always returns undefined, there'll never be anything included in the JSON stringified result, so the overall effect is that you get undefined. It's sort-of an anti-pattern to do this: if (something) { return whatever; } else { return somethingElse; } Your first function would be more idiomatic as: str = JSON.stringify(o,function(k,v) { return Object.isSealed(this) ? undefined : v; }); edit — note that JSON.stringify() calls your replacer function first with an empty key, and "v" equal to this a new wrapper object containing the object to be stringified (and note that that object is not sealed). That is, before chec

Categories : Javascript

Returning 'nil' from a Lua function in C vs returning 0 values
Yes, this is perfectly valid. If you're trying to request/assign more return values than there are (no matter whether you try to get one or ten), you'll get nil for the undefined ones (i.e. those not returned). function test1() return 5 end local a, b = test1() -- a = 5, b = nil function test2() return 1, 2 end local c, d, e = test2() -- c = 1, d = 2, e = nil function test3() end local f, g = test3() -- f = nil, g = nil You probably can't find it in Lua's source because it's no special case or anything. It's just Lua's generic way to handle return values. Update: The difference you've noticed when trying to print return values is the fact that this is not just an assignment. Of course there is a slight difference between returning nil and returning nothing at all - and it

Categories : C

Returning a Unicode string vs. Returning a normal string encoded as UTF-8?
UTF-8 is an encoding of the entire Unicode character set. It is backwards compatible with ASCII. For characters outside the ASCII set, multibyte encodings are used. All ASCII strings are Unicode strings. All Unicode strings are not ASCII strings.

Categories : Python

As we all know constructor is not having a returning type but in the code below constructor is returning...can any one explain
This: complex_1 complex_1::operator+(complex_1 c) is a definition of a class complex_1 member function (complex_1:: means this) that returns an object of type complex_1. c is not a constructor but an object of type complex_1 that is returned in this function.

Categories : C++

using the IN clause in SQL
I believe in JET this is valid syntax for an external database and is for referencing an external databases as described by the OP. For reference: http://en.wikibooks.org/wiki/JET_Database/Insert

Categories : SQL

Using [like] like in clause in SQL?
Try this one - Query: SELECT * FROM A WHERE EXISTS( SELECT 1 FROM B WHERE b_desc LIKE '%' + a_desc + '%' ) Output: id a_desc ----------- ---------- 2 hp 3 IBM Execution plan: Extended statistics: Update: SELECT A.*, B.* FROM A OUTER APPLY ( SELECT * FROM B WHERE b_desc LIKE '%' + a_desc + '%' ) B WHERE b_desc IS NOT NULL

Categories : SQL

PDO clause where using for
Change your function like this: public function check_siswa($noInduk) { $cnoInduk = count($noInduk); // error to hold the keys that are duplicate $error = Array(); for($i = 0; $i < $cnoInduk; $i++) { $sql = "SELECT no_induk FROM siswa WHERE no_induk = :noInduk"; $q = $this->db->conn_id->prepare($sql); $q->bindParam(':noInduk', $noInduk[$i], PDO::PARAM_INT); $q->execute(); if ($q->rowCount() > 0){ // if the key already exists then add it to the // error array $error[] = $noInduk[$i]; } } // there are some keys that exist already if (!empty($error)){ return $error; } // no duplicates return false else { return false; } } then for

Categories : PHP

The 'N' in the where clause of SQL
The N stands for "National Character" and it means that the content of the string is Unicode. You should be using Unicode (nchar/nvarchar) whenever you might come across proper names or other entities that can contain characters outside of the default ASCII character set. If you don't surround such strings with the N prefix, you will lose data. For example: SELECT N'ук ферт хер', 'ук ферт хер'; Results: ----------- ----------- ук ферт хер ?? ???? ??? You should also be sure to use the N prefix in your WHERE or other clauses against n(var)char columns. When you don't use the N prefix, you could suffer serious performance issues due to implicit conversion.

Categories : SQL

IN clause in SAS
It looks like you want to scan over all (selected) rows in the input data, and test whether any of them has ID = 'a'. You don't do this with an IN clause; that's for testing against a set of values for each row, as opposed to testing against one value for all rows. data _null_; set a (where=(id = &inp); if id = 'a' then do; put 'valid'; stop; end; run;

Categories : Sas



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.