A Simple Linq Query to return a Record from SQL Server

I have a table named Customers which contain columns like
Id   Col1   Col2   Col3   Col4   Col5
How do I write a Linq query to return the value of Col2 where Id=999

Hello,
It depends on what method you use to read data i.e. Data Context class, Entity Framework for SQL-Server we can get data directly from the database easily.
The following has two very simply examples using data context classes and the same came be done with Entity Framework which has an even more powerful version of data context implementation under 6 and above
Dim db As New DataClasses1DataContext
Dim theCustomer As Customer = db.Customers.Where(Function(c) c.CustomerID = 999).FirstOrDefault
If theCustomer IsNot Nothing Then
' use theCustomer which contains all columns
Else
' do not use, customer not located
End If
Dim theCustomer1 As Customer =
From c In db.Customers
Where c.CustomerID = 999
Select New Customer With
.CompanyName = c.CompanyName,
.ContactName = c.ContactName,
.Orders = c.Orders
).FirstOrDefault
Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem.

Similar Messages

  • One of the Column returned as NULL from SQL Server 2008

    Hi,
    I have written a stored procedure in SQL server 2008. The procedure reads data into a temporary table @MeterWiseConsumptionBetwDates as shown
    SELECT @sqlstatement =     'SELECT '''@MeterName''', CAST ( MAX('@Meterfield') AS FLOAT )-CAST ( MIN('@Meterfield') AS FLOAT )
                                  FROM KWH
                                  WHERE     KWH.timestamp BETWEEN @StDate AND @EndDate'
    INSERT INTO @MeterWiseConsumptionBetwDates(MeterName,Consumption)
    EXEC sp_executesql @sqlstatement, N'@StDate datetime, @EndDate datetime', @StDate, @EndDate
    Now when I execute the stored procedure in SQL Server Management Studio it returns all the columns from the table @MeterWiseConsumptionBetwDates, but when I execute the procedure in MII it returns the values in the Consumption column as null. The MeterName column is returned correctly in both the cases.
    Please help.
    Thanks

    Glad to hear that it is working.  You should be able to use
    execute <proc name> '[SD]'
    [SD] and [ED]
    are the query date tokens, so whatever you have assigned on the Date Range tab will be passed to the query.
    Jamie
    Edited by: Jamie Cawley on May 9, 2011 9:40 AM

  • Inserting Records from SQL Server to Oracle using trigger

    Hi All,
    I have 2 Database SQL Server And Oracle 12c.
    Now I want to Implement such functionality by which i just need to insert data in SQL Server 
    and data also inserted in Oracle.
    How can i do it?
    I found LinkServer concept but i'm not much aware of it.
    Regards,
    Rahul

    If it were me I would use replication.
    Andy Tauber
    Data Architect
    The Vancouver Clinic
    Website | LinkedIn
    This posting is provided "AS IS" with no warranties, and confers no rights. Please remember to click
    "Mark as Answer" and "Vote as Helpful" on posts that help you. This can be beneficial to other community members reading the thread.

  • Query is returning multiple records for a bank account id and party id

    Hi All,
    I am not getting why this query is returning multiple records for a particular bank account id and party id:
    SELECT instrument_payment_use_id
    ,instrument_type
    ,instrument_id
    ,start_date
    ,ext_pmt_party_id
    FROM iby_pmt_instr_uses_all
    WHERE instrument_id =:lv_num_ext_bank_account_id
    and exists (select 1 from iby_external_payees_all b where PAYEE_PARTY_ID= :lv_num_party_id and b.ext_payee_id = ext_pmt_party_id)
    I want above values to be used in api iby_disbursement_setup_pub.set_payee_instr_assignment in R12.
    Please help asap.
    Thanks

    O/P of query run for
    SELECT rowid, instrument_payment_use_id
    FROM iby_pmt_instr_uses_all
    WHERE instrument_id =6642
    AND EXISTS (
    SELECT 1
    FROM iby_external_payees_all b
    WHERE payee_party_id= 85470
    AND b.ext_payee_id = ext_pmt_party_id);
    is below:
    Rowid     INSTRUMENT_PAYMENT_USE_ID
    AABiDXAGIAABhiKAAS     236586
    AABiDXAGRAABSjtAAz     148437
    The version is R12

  • I want to query oracle database from sql server can anyone tell steps 2 fo

    i want to query oracle database from sql server can anyone tell steps 2 followed
    i tried with linked servers but it is throwing errors can anyone hepl in this regard
    The operation could not be performed because the OLE DB provider 'MSDAORA' was unable to begin a distributed transaction.
    OLE DB error trace [OLE/DB Provider 'MSDAORA' ITransactionJoin::JoinTransaction returned 0x8004d01b].

    First of all - you are in the wrong forum.
    Look either for the Database general or search for Transparant / Heterogenous Gateways.
    cu
    Andreas

  • I want to query oracle database from sql server can anyone tell steps 2 fol

    i want to query oracle database from sql server can anyone tell steps 2 followed
    i tried with linked servers but it is throwing errors can anyone hepl in this regard
    The operation could not be performed because the OLE DB provider 'MSDAORA' was unable to begin a distributed transaction.
    OLE DB error trace [OLE/DB Provider 'MSDAORA' ITransactionJoin::JoinTransaction returned 0x8004d01b].

    First of all - you are in the wrong forum.
    Look either for the Database general or search for Transparant / Heterogenous Gateways.
    cu
    Andreas

  • How many query possible in 1 second at Sql Server ?

    Hello
    I have 30,000 records. Table have 10 columns. Columns have indexes if column at where condition. And select question will give 20-30 records as result. (select column1, column2,...... column10 from table where columnSecondID=2I. I will use hosting standart
    plane. 
    How many query possible in 1 second at Sql Server 2008 ?
    How many query possible in 1 second at Sql Server 2012 ?
    How many user can visit my web site ?

    Hello
    I have 30,000 records. Table have 10 columns. Columns have indexes if column at where condition. And select question will give 20-30 records as result. I will use hosting standart plane. 
    How many query possible in 1 second at Sql Server 2008 ?
    How many query possible in 1 second at Sql Server 2012 ?
    How many user can visit my web site ?
    That's hard to say. One second for CPU is quite high time and CPU can do lot of work in that time. again, this is relative and depends on what the query is.
    The biggest bottleneck in performance is - Disk IO system. In general, if  the required data is in memory, it can help significantly in improving the performance.
    Remember, CPU will be doing other processing work while it is fetching the data from disk.
    What you need to is  - load test or stress your server. There are some tools available for you to do it. 
    RML : https://support.microsoft.com/en-us/kb/944837?wa=wsignin1.0
    distributed replay : https://msdn.microsoft.com/en-us/library/ff878183.aspx
    to test IO : http://www.brentozar.com/archive/2008/11/storage-performance-testing-with-sqlio/
    read this : http://www.brentozar.com/archive/2012/06/load-test-sqlserver/
    You also need to look at Max worker thread limitations. this depends on the server configuration(64 bit/32 bit) and other factors...
    https://technet.microsoft.com/en-us/library/ms187024%28v=sql.105%29.aspx
    one problem that can happend is thread pool starvation where there are too many connections
    happening if your server cannot keep up with the workload.. like if your cpu is working in processing the queries and cannot accept new connections..
    watch this good youtube video on thread pool starvatioin :
     https://www.youtube.com/watch?v=XJ67oHBM2Hw
    Hope it Helps!!

  • Have trouble query after creating a linked server from SQL Server 2008 to EXCEL 2007

    I created a linked server from SQL Server 2008 Management Studio Express to an EXCEL 2007 workbook using:
    sp_addlinkedserver @server='LSERVER_EX0', @srvproduct='EXCELDATA', @provider='Microsoft.ACE.OLEDB.12.0', @datasrc='C:\Temp\abc.xlsx', @provstr='EXCEL 12.0'
    The linked server LSERVER_EX0 was created, but I cannot see any table(excel sheet), and when i ran the following to query tables,
    sp_tables_ex 'LSERVER_EX0'
    I got:Cannot obtain the schema rowset "DBSCHEMA_TABLES" for OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "LSERVER_EX0". The provider supports the interface, but returns a failure code when it is used.
    Any hint why?
    on another note, i was able to import the EXCEL sheets using the Import and Export Data wizard, but i cannot control the column data type and size in this way.

    Open management studio, goto "Server Objects"->"Linked Servers"->Providers, select the provider you use, right click it and in provider options, check "Allow inprocess".

  • How to execute procedure returning data rows from sql plus

    Hi,
    I want to execute a stored procedure that returns data rows from sql plus. please let me know the syntax for the same.
    Thanks,
    YG

    user13065317 wrote:
    Even if i get the result set into the cursor, do i have to do normal fetch into all the coumn variables within a loop
    But suppose no of columns in my result set varies depending on a parameter to the stored procedure.
    Is there any straightforward way to retrieve all the data irrespective of no of columns in the result set.There is no such thing as a "+result set+". Oracle does not create a temporary data set in memory that contains the results of your query. What would happen if this result set is a million rows and is too large to fit into memory? Or there are a 100 clients each with a 100,000 row result set?
    This is not scalable. You will be severely limited in the number and sizes of these "+result sets+" that can be created in server memory.
    A cursor is in fact a "program" that is created by compiling the SQL source code that you provide. This source code is parsed and compiled into what Oracle calls an execution plan. This is nothing but a series of instructions that the cursor will execute in order to return the rows required.
    Thus the result set is actually the output from a cursor (a program). Likewise, bind variables are the input parameters to this program.
    All SQLs are parsed and compiled as cursors and stored in the SQL Shared Pool. Oracle gives you handle in return to use to address this cursor - bind values to it, execute it, describe the output structure returned by the cursor, and fetch the output from the cursor.
    On the client side, this handle is used in different ways. In PL/SQL alone, this cursor handle can be used as an implicit cursor (you do not even see or use the cursor handle in your PL/SQL code). Or you can use a PL/SQL cursor variable. Or a DBMS_SQL cursor variable. Or a reference cursor variable.
    Why so many different client structures for the very same SQL cursor handle returned by Oracle? Because to allow you, the programmer, all kinds of different features and flexibility.
    The ref cursor feature is the ability to pass this cursor handle around, not only between PL/SQL code, but also from PL/SQL to the actual client process (Java. VB, SQL*Plus, TOAD, etc).
    The primary thing to remember - irrespective of what the client calls this (e.g. ref cursor, SQL statement handle, etc), this all refers to the same SQL cursor in the Shared Pool. And that this SQL cursor is a program that outputs data, and not a result set in itself.

  • Can I preserve carriage returns in a string variable from SQL Server?

    I have an OLE data source that pulls data from sql server via a SELECT query.  One of the fields is an NVARCHAR(max) which goes into a string variable which is later used in an expression.  I am noticing that in the expression, carriage returns
    / line breaks in this field are being lost.  Does anyone know how I can preserve these in the expression?

    Thanks everyone for the suggestions.  I am certain there are both \r and \n in the database as when I print the field and then copy/paste to textedit to show the hidden characters, I can see both the CR and LF's.  
    I have implemented a workaround that is by no means elegant, but it gets the job done.
    I found that \r and \n will evaluate in an expression but if they are part of another string variable, SSIS escapes them. My workaround was to change my OLE_DB select statement (which fetches the custom SQL query) to explicitly change the hidden characters
    to '\r' and '\n' respectively:
    SELECT REPLACE(REPLACE([CUSTOM_SQL],char(13),'\r'),char(10),'\n')
    Then, in my SSIS expression, I de-escaped these characters:
    REPLACE(REPLACE(@[User::vAlertCustomSQL],"\\r","\r"),"\\n","\n")
    Now when the expression is executed, the SQL is formatted correctly and oddly placed comments in the query no longer break the query.  

  • Error with date field when inserting records into sql server from webdynpro

    Dear SDN's,
    I am trying to insert the records into sql server through my webDynpro program.
    I have created a date field in a dictionary with the datatype date.
    In my webdynpro program to insert the date i am following the below format.
    String dateString = "2006/12/10";
          java.util.Date d=new java.util.Date(dateString);
          java.sql.Date <b>date</b> = new java.sql.Date(d.getTime());
    int i=stmt.executeUpdate("INSERT INTO TRAVEL_HEADER(TRQID,PROJECTID,<b>REQDT</b>,ADVCE,ETADV,PURTR) values(21, '555-1212', '" + <b>date</b> + "', 5000, '20060501','hi')");
    when i try to execute it, it gives the following error.
    <b>com.sap.sql.log.OpenSQLException: The SQL statement "INSERT INTO "TRAVEL_HEADER" ("TRQID","PROJECTID","REQDT","ADVCE","ETADV","PURTR") VALUES (21,'555-1212','2006-12-10',5000,'20060501','hi')" contains the semantics error[s]: - type check error: new value (element number 3 (CHAR)) is not assignable to column  >>REQDT<< (DATE)</b>
    Please correct me.
    Your help will be appreciated.
    Regards,
    Sireesha.B

    Hi,
    int i=stmt.executeUpdate("INSERT INTO TRAVEL_HEADER(TRQID,PROJECTID,REQDT,ADVCE,ETADV,PURTR) values(21, '555-1212', 'date', 5000, '20060501','hi')");
    try like this.
    I Think in SQL the general format to take date as input like this.
    INSERT INTO X VALUES ('10/30/56')
    thaks,
    Lohi.

  • Help with translating SQL query from SQL Server syntax to Oracle syntax

    Hi,
    is it someone that can help me translate following SQL query from SQL Server syntax to Oracle syntax.
    SELECT ID,
    [LMT(MTR)] = MAX(case when TYPE = 'LMT' then VALUE end),
    [AAD(KGM)] = MAX(case when TYPE = 'AAD' then VALUE end),
    [VOL(MTQ)] = MAX(case when TYPE = 'VOL' then VALUE end)
    FROM yourtable
    GROUP BY ID
    Your help is highly appreciated, thanks in advance.

    Like this,
    SELECT ID,
    MAX(case when TYPE = 'LMT' then VALUE end) LMT_MTR,
    MAX(case when TYPE = 'AAD' then VALUE end) AAD_KGM ,
    MAX(case when TYPE = 'VOL' then VALUE end) VOL_MTQ
    FROM yourtable
    GROUP BY ID-Arun

  • If i transfer some records from one server to another server,

    hi to all......
    5........If i transfer some records from one server to another server, will that save in change request or work bench request?
    thanks and regards,
    k.swaminath

    Hi friend my suugession is , if u r transfering records from one client to another or changing anything in the active pgm, it will save under  change request...
    But if u r transfering records from one server to server it will save under work bench request...

  • 8i Query not returning expected records

    Using Oracle 8i (8.1.7), a basic spatial query is not returning all the expected results. Table1 contains a variety of polygons; table2 is simply a set of rectangles. I want to return all objects from table1 that intersect a particular rectangle. The query below mostly works, but misses out some objects. On my system, 38 objects are returned where about 41 are expected; on the client system (which does not have identical data) the problem appears to be much worse, with hardly any objects being returned. The missing objects are clearly visible on the map, surrounded on all sides by objects which have been selected correctly. Help?
    Select t1.id from table1 t1, table2 t2
    where t1.IsCurrent = -1
    and (sdo_relate(t1.geoloc, t2.geoloc, 'mask=ANYINTERACT querytype=WINDOW') = 'TRUE')
    AND (t2.ID in ('001'));

    Hi,
    When the non-spatial predicate is dropped, you mentioned the
    objects are not missing. This means the spatial index (which will
    surely be used in this case) should be returning correct results.
    But it is possible the index is not used when other predicates are
    specified. Please look at the "execution plan" in both cases (when the
    objects are missing/not missing).
    Rewrite the query as:
    select /*+ ORDERED INDEX(t1 <spatial_index_name>) */ t1.id from t2, t1
    This should ensure a spatial-index-based evaluation.
    Let us know the execution plans and the behavior in either case.
    Btw, one thing to check is your tolerance values in
    user_sdo_geom_metadata.
    - Ravi.

  • Query Not Returning Enough Records

    have two tables that I am trying to join together. 
    The first table shows the income for each department of the store broken down by period like this:
    Store_Data:
    Store_Type  Dept    Year  Period  Sales
    Grocer      Produce   11  01      31865.00   
    Grocer      Produce   11  02      32525.00   
    Grocer      Produce   11  03      37490.00   
    Grocer      Meat      11  01      224.00   
    Grocer      Dairy     11  02      5850.00   
    Grocer      Dairy     11  03      33209.92   
    Grocer      Dry       11  03      1000.00
    The second table contains a record for each store showing it's goal, like this:
    Goal_Data:
    Store_Type  Dept    Year  Amount
    Grocer      Produce   11  157192.00
    Grocer      Canned    11  0.00
    Grocer      Paper     11  146820.00
    Grocer      Meat      11  2168.00
    Grocer      Dairy     11  50000.00
    Grocer      Frozen    11  29464.00
    Grocer      Pet       11  330096.00
    Grocer      Dry       11  1716.00
    Grocer      Pharmacy  11  0.00
    Grocer      Misc      11  6668.00
    Now, I have a query to join the two tables.  What I want is for all the records in the second table, whether or not there is a corresponding record in the first (such as 'Meat' and 'Dairy').
    I have to filter on Store_Data.Store_Type, Store_Data.Year, Store_Data.Period
    Crystal is outputting the following SQL:
    SELECT DISTINCT
        Store_Data.Store_Type,
        Store_Data.Dept,
        Store_Data.Year,
        Store_Data.Period,
        Store_Data.Sales,
        Goal_Data.Amount
    FROM  
        Store_Data
        RIGHT OUTER JOIN Goal_Data
            ON ((Goal_Data.Dept=Store_Data.Dept) AND
            (Goal_Data.Store_Type=Store_Data.Store_Type))
            AND (Goal_Data.Year=Store_Data.Year)
    WHERE 
        Store_Data.Store_Type='Grocer'
        AND Store_Data.Year='11'
        AND (Store_Data.Period='01'
            OR Store_Data.Period='02'
            OR Store_Data.Period='03')
    But I'm only getting the records from the Store_Data table (and records in Goal_Data where the "ON" fields match).  Testing in SQL Server verifies that the query is producing incorrect output.
    What do I need to change to do what I'm wanting to do?

    It looks like the thread is going to take a left turn just about now.
    The problem appears to be that, for the query to work properly, the filter for the period has to be in the joins "ON" clause.
    This I accept.
    And, apparently, trhe only way to get a parameter value to go into that area is by using a stored procedure.
    To that end, I have created a Stored Procedure which takes three parameters, "Store_Type", "Year", and "Quarter"
    I have verified that the results are what I need.  I plugged the stored procedure into my report (which is technically a sub-report) and it asked me for the values of the parameters.  Entering them in, I do get a result that I would expect.
    Everything good so far.
    Now, about those parameters (both for the Storeed Procedure as well as the report).  As I said, the report that I have been working is actually a sub-report, one of five which will be on the main report.  Each report will require the same three parameters, two of which (year and quarter) need to be selected by the user and will feed the same values to all five sub-reports.  The third parameter should be "hard-coded" to each particular sub-report.
    Now for the issue (the main point being that I am unfamiliar with CR and Stored Procedures)...
    The way things are going now, when all is said and done, it looks like the user will be required to enter in the year and quarter for each sub-report (the Store_Type will be there too, but it will have a default value).  That's the user typing in '2012' for the year five times and '1' for the quarter five times.  This is unacceptable.
    So, how do I create a single Year parameter and a single Quarter parameter that will feed all five reports?
    Apparently trying to code it in the Report Selection Formula is not the right path.
    So, can someone either walk me through the process, or point me to a tutorial where the process is explained?
    TIA

Maybe you are looking for

  • Document/literal web service

    Currently I deployed an rpc/encoded ejb web service. The ejb handles the request and response using Java methods. I can change this web service to document/literal by changing the style=document in Servicegen. Does this mean that I have to handle the

  • Transfer pictures from iPhoto to Apple Mail

    Ok maybe it's me. But when I sue iPhoto to send pictures by email I select the photos I want in iPhoto, click the "send by email" button and it opens Apple mail. All that's cool. The problem is that it puts the pictures in the body of the email "whic

  • Color and depth lost when reading PNG

    Hello, I'm using IMAQ Read Image And Vision Info.vi to read a PNG saved with IMAQ Write Image And Vision Info.vi. The saved image is 24 bits, color. When I open the image and display it using an image control, it shows up as an 8-bit grayscale. How d

  • Elements 9 will not read RAW

    I've been here for days and tried everything. That's ok, I don't have a life and I'll be dead soon. Elements 9 won't load the RAW 6.3 update. Using a converter seems like my only option. Makes perfect sense, load my drive up with gigantic duplicate f

  • Please, please help find "orphaned" web pages

    I have spent the last 4 hours trying to delete "orphaned" web pages.  Several years ago I created some web pages using Front Page and then uploaded them to ftpmysite.verizon.net using an FTPClient.  Then I dumped Verizon's web suite altogether becaus