Querying SQL db based off of values in a CSV and exporting filtered list to a new CSV

Hello, we use Office365 for our student e-mail accounts and are trying to appropriately license those accounts based on if they are currently enrolled or not (currently enrolled get the full license with OneDrive, SharePoint, Lync, Office download etc. while
non-currently enrolled get e-mail only).  I have exported a list of UserPrincipalNames from Office365 to a CSV that have a particular license applied.  I want to compare that list against a SQL view that will identify if those UserPrincipalNames
(found under the "Email" column in the SQL database) are currently registered for classes or not (we have a "CurrentlyRegistered" column populated with a "0" for not registered and a "1" for registered"). 
I then need to export the filtered list of UserPrincipalNames to a different CSV so that I can use that second CSV to change the license in Office365.
For example, I export a list of accounts from Office 365 that have the e-mail only license applied to a CSV named "Exchange.csv" that has a single column of data with a header of "UserPrincipalName".  I want to compare the accounts
in the "Exchange.csv" to our SQL view (which among other columns, has one named "Email" that matches the values of "UserPrincipalName" and a "CurrentlyRegistered" column) to see if any have changed status to being currently
enrolled so that I can flip their license to the full license. I would know this by returning any accounts that have a "1" in the "CurrentlyRegistered" column and saving those to a CSV named "Full.csv" that would have two columns
with headers "Email" and "CurrentlyRegistered".
I need to know how to connect to SQL from PowerShell and return the filtered list of accounts that have changed status.  I am hoping for something like:
$constring = "Server=MyServer\Instance;Database=StudentEmails;Trusted_Connection=True"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = $constring
$SqlCommand = New-Object System.Data.SqlClient.SqlCommand
$SqlCommand.CommandText = $query
$SqlCommand.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCommand
$DataSet = New-Object System.Data.DataSet
$SqlConnection.Open()
$SqlAdapter.Fill($DataSet)
$SqlConnection.Close()
$DataSet.Tables[0]
Remove-Item C:\O365Operations\CSVs\Full.csv
$query = Import-Csv C:\O365Operations\CSVs\Exchange.csv | ForEach-Object {Invoke-Sqlcmd -Query "SELECT [Email],[CurrentlyRegistered] FROM [StudentEmails].[dbo].[v_StudentEmailAccounts] WHERE CurrentlyRegistered = '1'"} | Export-Csv C:\O365Operations\CSVs\Full.csv
-Append}
Am I anywhere close with this?
Thanks,
Jeremy Hawks
Systems Administrator @ Green River College

My CSV has a single column with a the #Type in the first line, the header of "UserPrincipalName" in the second line and the rest of the lines having a single e-mail address, similar to:
#TYPE Selected.Microsoft.Online.Administration.User
UserPrincipalName
[email protected]
[email protected]
[email protected]
The "Email" column in SQL will have some matching values to the "UserPrincipalName" column in the CSV. 
So if any of the (UserPrincipalName in CSV) values match the values found in the column (Email in SQL) then I want to export those e-mail addresses to a CSV so that I can use the new CSV to change the licenses in Office 365.
When I run your modified code I get the following:
PS C:\Windows\system32> $csv=Import-Csv C:\O365Operations\CSVs\Test.csv
$csv|select email
foreach($User in $csv){
     # find user
     if($DataTable|?{$_.Email -eq $user.Email}){
         Write-Host "User found: $($user.email)" -fore green
         #Select Email,CurrentlyRegistered | Export-Csv C:\O365Operations\CSVs\IW2.csv -Append
     }else{
        Write-Host "User NOT found: $($user.email)" -fore red
email
User NOT found:
User NOT found:
User NOT found:
User NOT found:
User NOT found:
User NOT found:
User NOT found:
User NOT found:
User NOT found:
User NOT found:
User NOT found:
User NOT found:
User NOT found:
User NOT found:
User NOT found:
User NOT found:
User NOT found:
User NOT found:
User NOT found:
User NOT found:
User NOT found:
User NOT found:
User NOT found:
User NOT found:
User NOT found:
User NOT found:
User NOT found:
User NOT found:
User NOT found:
User NOT found:
User NOT found:
User NOT found:
User NOT found:
User NOT found:
User NOT found:
User NOT found:
User NOT found:
User NOT found:
User NOT found:
User NOT found:
User NOT found:
User NOT found:
User NOT found:
User NOT found:
User NOT found:
User NOT found:
User NOT found:
User NOT found:
User NOT found:
User NOT found:
User NOT found:
User NOT found:
User NOT found:
User NOT found:
User NOT found:
User NOT found:
PS C:\Windows\system32>
If I change the command from
$csv|select email
to
$csv|select UserPrincipalName
Then I get a full listing of the e-mails in the CSV with none filtered out (so it is not comparing it to the returned data from the SQL table.
Suggestions?
Jeremy Hawks Systems Administrator @ GRC

Similar Messages

  • Out of memory Error while querying SQL Script based Calculation View

    Hi All,
    I wanted to test the performance of Graphical and SQL Script based Calculation views.
    Created Graphical (CA_GRPH) and SQL Script (CA_SQL) Calculation views.
    Analytic View (AN_GRPH) for both Calculation views are the same which is Graphical based (90 Attributes and 5 Measures)
    In Analytic View data foundation I have a Fact table which has 1.5 Billion records and 9 Dimension Tables –collectively 500 million records (7 Attribute Views). 9 Referential joins with cardinality N:1 and 1 Referential join with cardinality N:N.
    I wanted to keep (CA_GRPH) and (CA_SQL) as a base Calculation views and leverage those to create various calculation views (Will be creating different Calc views for respective Business segments)
    In order to test this I have created below calc views on top of base calc views.
    Graphical Based: Created (CA_GRAPH_XYZ) by having CA_GRPH in projection with 30 Calculated Columns. – This retrieves data in 13 secs
    SQL Script Based: Created (CA_GRPH_ABC) by having CA_SQL in projection view with 30 calculated columns – This errors out after 1.50 mins.
    Could not execute 'SELECT "COLUMN_A","COLUMN _B"," COLUMN _C"," COLUMN _D", SUM("COLUMN _REVENUE") AS ...' in 1:50.480 minutes .
    SAP DBTech JDBC: [2048]: column store error:  [2048] column store error: search table error: [1000002] Error executing physical plan: exception 1000002:
    ltt/impl/memory.cpp:63
    Out of memory ; $size$=1507711; $name$=ihm; $type$=pool; $inuse_count$=170104; $allocated_size$=219215007925
    exception 1000002:
    Any suggestion / help in fixing this issue will be greatly appreciated.
    Regards,
    Av

    Hi Raj,
    Thanks for your time, please find edited snap hot of Analytic View (AN_GRPH) below,
    Calculation view(CA_SQL)
            /********* Begin Procedure Script ************/
    BEGIN
           var_out =
         SELECT
                "COLUMN_1"
                "COLUMN_2",
                "COLUMN_84",
                "COLUMN_85;",
                SUM("REVN") AS "REVN",
                SUM("MGN") AS "MGN",
                SUM("ORD_QTY") AS "ORD_QTY",
                SUM("SYS_QTY1") AS "SYS_QTY1",
                SUM("SYS_QTY") AS "SYS_QTY"
    FROM
          "_SYS_BIC"."XYZ/AN_GRPH"
    GROUP BY
                "COLUMN_1"
                "COLUMN_2",
                "COLUMN_84",
                "COLUMN_85";
    END
    /********* End Procedure Script ************/
    Later i have built one more Calculation view(CA_GRPH_ABC) using (CA_SQL)in projection. i have 30 calculated measures in this final calc view. this final calc view is throwing above mentioned error.
    Not sure if i can use SQL script based calc view in graphical based calc views?
    Regards,
    AV

  • I'm trying to transfer iTunes and it's based off an old email account. How can I transfer to my new email account.

    I'm trying to transfer iTunes and it's based off an old email account. How can I transfer to my new email account.

    In addition I don't remember my old password.

  • How to set query SQL on db throug item value?

    Hi
    I've two pages:
    the first page contain the item textfield value (P1_NAME) and second page contain the query SQL.
    Where the query sql instruction insert in the second page rendering?
    In the Items, in the buttons, in the computation, in the process?
    How display the results of query?
    Help Me!!!

    On re-reading I think I get it. When you open the second page, which could be anywhere, you'll have to tell me (could be a Branch, could be a linked column in a report, could be triggered from a button). Whervever the code that opens the second page is, you will see a setting labelled "Target is a" and the chosen selection will be "Page in this Appication" Right under that, you will see two other fields labelled "Set These Items" and "With These Values" this will let you set whatever items you wish on the page that you are opening.

  • Sub totals based off the value of a dimension

    Hi,
    I have a requirement to apply sub totals to a dimension at certain levels of a hierarchy.
    From what we've implemented, the typical Level-Based Hierarchy has been replaced by a Flat Hierarchy, so instead of accounts appearing at different levels and in different columns (I.E Level 31, Level 30, Level 29 ... ), they appear in 1 single column. A seperate column called Node Depth determines the level at which these accounts sit.
    Essentially, I just want to show sub totals for values 2 and 3 in the Node Depth column.
    Is there a way to do this in OBIEE? I've only been able to get ALL subtotals to appear.
    Thanks

    Hi Chris,
    You can either use the FILTER...USING... function in answers or you can create distinct, filtered LTSs in the RPD which will then represent your node depth. I.e. you'd have, in your example, 8 LTSs with differing fragmentation content of "Node Depth" = 1 ... = 8

  • I'm using Windows Firewall and even turning it off does not change the situation and I can not access any new emails.

    I was using TB on my XP machines and they went down so I was forced to move to a Vista based laptop. It eventually crashed and so I converted my computer from Vista to win 7, Home premium. In both iterations, I have been able to set up TB and transfer all the data & emails that was in them at the time ( from the bood drive that was in the xp machine). but since that time I have not been able to access anything new after that date. It will neither send nor receive emails from both gmail and cox.net accounts that I have. I've attached the settings below. I tried changing some things on [email protected], so that info is obviously wrong.
    I've tried deleting TB but apparently have not been able to remove all the data because when I reload it, it just comes back immediately the way it was.
    Any help would be appreciated. I really like how TB works and would love to be able to use it again.
    Jim
    Application Basics
    Name: Thunderbird
    Version: 31.3.0
    User Agent: Mozilla/5.0 (Windows NT 6.1; rv:31.0) Gecko/20100101 Thunderbird/31.3.0
    Profile Folder: Show Folder
    (Local drive)
    Application Build ID: 20141127140543
    Enabled Plugins: about:plugins
    Build Configuration: about:buildconfig
    Memory Use: about:memory
    Mail and News Accounts
    account1:
    INCOMING: account1, , (imap) imap.googlemail.com:993, SSL, passwordCleartext
    OUTGOING: smtp.googlemail.com:465, SSL, passwordCleartext, true
    account2:
    INCOMING: account2, , (none) Local Folders, plain, passwordCleartext
    account3:
    INCOMING: account3, , (imap) imap.googlemail.com:143, plain, passwordCleartext
    OUTGOING: smtp.googlemail.com:465, SSL, passwordCleartext, true
    account4:
    INCOMING: account4, , (imap) imap.googlemail.com:993, SSL, passwordCleartext
    OUTGOING: smtp.googlemail.com:465, SSL, passwordCleartext, true
    account5:
    INCOMING: account5, , (imap) imap.googlemail.com:993, SSL, passwordCleartext
    OUTGOING: smtp.googlemail.com:465, SSL, passwordCleartext, true
    account6:
    INCOMING: account6, , (imap) imap.cox.net:993, SSL, passwordCleartext
    OUTGOING: smtp.cox.net:465, SSL, passwordCleartext, true
    Crash Reports
    Extensions
    Important Modified Preferences
    Name: Value
    browser.cache.disk.capacity: 358400
    browser.cache.disk.smart_size.first_run: false
    browser.cache.disk.smart_size.use_old_max: false
    browser.cache.disk.smart_size_cached_value: 358400
    extensions.lastAppVersion: 31.3.0
    font.internaluseonly.changed: true
    font.name.monospace.el: Consolas
    font.name.monospace.tr: Consolas
    font.name.monospace.x-baltic: Consolas
    font.name.monospace.x-central-euro: Consolas
    font.name.monospace.x-cyrillic: Consolas
    font.name.monospace.x-unicode: Consolas
    font.name.monospace.x-western: Consolas
    font.name.sans-serif.el: Calibri
    font.name.sans-serif.tr: Calibri
    font.name.sans-serif.x-baltic: Calibri
    font.name.sans-serif.x-central-euro: Calibri
    font.name.sans-serif.x-cyrillic: Calibri
    font.name.sans-serif.x-unicode: Calibri
    font.name.sans-serif.x-western: Calibri
    font.name.serif.el: Cambria
    font.name.serif.tr: Cambria
    font.name.serif.x-baltic: Cambria
    font.name.serif.x-central-euro: Cambria
    font.name.serif.x-cyrillic: Cambria
    font.name.serif.x-unicode: Cambria
    font.name.serif.x-western: Cambria
    font.size.fixed.el: 14
    font.size.fixed.tr: 14
    font.size.fixed.x-baltic: 14
    font.size.fixed.x-central-euro: 14
    font.size.fixed.x-cyrillic: 14
    font.size.fixed.x-unicode: 14
    font.size.fixed.x-western: 14
    font.size.variable.el: 17
    font.size.variable.tr: 17
    font.size.variable.x-baltic: 17
    font.size.variable.x-central-euro: 17
    font.size.variable.x-cyrillic: 17
    font.size.variable.x-unicode: 17
    font.size.variable.x-western: 17
    mail.openMessageBehavior.version: 1
    mail.winsearch.firstRunDone: true
    mailnews.database.global.datastore.id: ad1f0fc4-c403-47b2-90a5-b85ce5567e0
    mailnews.database.global.views.conversation.columns: {"threadCol":{"visible":true,"ordinal":"1"},"flaggedCol":{"visible":true,"ordinal":"3"},"attachmentCol":{"visible":false…
    mailnews.database.global.views.global.columns: {"threadCol":{"visible":true,"ordinal":"1"},"flaggedCol":{"visible":true,"ordinal":"3"},"attachmentCol":{"visible":false…
    network.cookie.prefsMigrated: true
    places.database.lastMaintenance: 1419701657
    places.history.expiration.transient_current_max_pages: 93896
    plugin.importedState: true
    security.default_personal_cert: Select Automatically
    security.disable_button.openCertManager: false
    security.disable_button.openDeviceManager: false
    Graphics
    Adapter Description: ATI Radeon 3100 Graphics
    Vendor ID: 0x1002
    Device ID: 0x9613
    Adapter RAM: 256
    Adapter Drivers: atiumdag atidxx32 atidxx64 atiumdva atiumd64 atiumd6a atitmm64
    Driver Version: 8.632.1.2000
    Driver Date: 8-17-2009
    Direct2D Enabled: Blocked for your graphics driver version. Try updating your graphics driver to version 10.6 or newer.
    DirectWrite Enabled: false (6.2.9200.16571)
    ClearType Parameters: D [ Gamma: 2200 Pixel Structure: R ClearType Level: 100 Enhanced Contrast: 300 ] D [ Gamma: 2200 Pixel Structure: R ClearType Level: 100 Enhanced Contrast: 300 ]
    WebGL Renderer: false
    GPU Accelerated Windows: 1/1 Direct3D 9
    AzureCanvasBackend: skia
    AzureSkiaAccelerated: 0
    AzureFallbackCanvasBackend: cairo
    AzureContentBackend: cairo
    JavaScript
    Incremental GC: 1
    Accessibility
    Activated: 0
    Prevent Accessibility: 0
    Library Versions
    Expected minimum version
    Version in use
    NSPR
    4.10.6
    4.10.6
    NSS
    3.16.2.3 Basic ECC
    3.16.2.3 Basic ECC
    NSS Util
    3.16.2.3
    3.16.2.3
    NSS SSL
    3.16.2.3 Basic ECC
    3.16.2.3 Basic ECC
    NSS S/MIME
    3.16.2.3 Basic ECC
    3.16.2.3 Basic ECC

    Hi Andre V.,
    When having iTunes Store connectivity issues, the following articles provide the best solutions:
    Can't connect to the iTunes Store
    http://support.apple.com/kb/TS1368
    iTunes: Advanced iTunes Store troubleshooting
    http://support.apple.com/kb/TS3297
    Thanks,
    Matt M.

  • How can I lookup text values in a column and display a list of corresponding names from another column, sorted by values?

    My spreadsheet looks like this:
              Monday     Tuesday     Wednesday
    Name 1     OFF          4:30 PM     4:30 PM
    Name 2     5 PM     OFF          4:30 PM
    Name 3     4:30 PM     5 PM     OFF
    Name 4     4 PM     OFF          OFF
    I would like to create a spreadsheet for each day that will display the values sorted by time, as follows (e.g. Monday):
    Name     In Time
    Name 4     4 PM
    Name 3     4:30 PM
    Name 2     5 PM
    Any help would be greatly appreciated. Thanks!

    Here's an example, using the provided data:
    I've set the alignment on Main to Automatic (except for row 1) to distinguish between numeric and quasi numeric values (aligned right) and text (aligned left). This is a visual aid to developing the table, and would likely be changed for appearance in the end version.
    Columns E, F and G of Main are index columns listing the RANK of numeric/date and time values in columns A, B and C respectively. Text values cause RANK to throw an error, which is caught by IFERROR, which returns a value of 999, chosen to be well above any of the RANK values returned. A small amount ( ROW()/100000 ) is added to each result to prevent duplicate results is cases like column D, where duplicate times appear.
    Formula: Main::E2: =IFERROR(RANK(B2,B,1),999)+ROW()/100000
    Fill down the column, and right to column G.
    These columns may be hidden.
    The three daily columns use a single formula each, revised to match the index columns from which they determine the row containing each piece of data to be copied, and to match the columns from which they retrieve that data. The formulas from row 2 of these tables are listed here in the order (left to right) that they are used in the second row of tables above. Parts that are edited from one formula to another are shown in bold.
    =IF(SMALL(Main :: $E,ROW()-1)>999,"",OFFSET(Main :: $A$1,MATCH(SMALL(Main::$E,ROW()-1),Main :: $E,0)-1,0))
    =IF(SMALL(Main :: $E,ROW()-1)>999,"",OFFSET(Main :: $A$1,MATCH(SMALL(Main::$E,ROW()-1),Main :: $E,0)-1,1))
    =IF(SMALL(Main :: $F,ROW()-1)>999,"",OFFSET(Main :: $A$1,MATCH(SMALL(Main::$F,ROW()-1),Main :: $F,0)-1,0))
    =IF(SMALL(Main :: $F,ROW()-1)>999,"",OFFSET(Main :: $A$1,MATCH(SMALL(Main::$F,ROW()-1),Main :: $F,0)-1,2))
    =IF(SMALL(Main :: $G,ROW()-1)>999,"",OFFSET(Main :: $A$1,MATCH(SMALL(Main::$G,ROW()-1),Main :: $G,0)-1,0))
    =IF(SMALL(Main :: $G,ROW()-1)>999,"",OFFSET(Main :: $A$1,MATCH(SMALL(Main::$G,ROW()-1),Main :: $G,0)-1,3))
    Each of the formulas is filled down its column.
    Each of the functions used is described in the iWork Formulas and Functions User Guide, a useful resource to have on hand when you are writing (or attempting to 'decode') Numbers formulas, The guide (and the Numbers '09 User Guide) may be downloaded from the Help menu in Numbers '09.
    Regards,
    Barry

  • How can I lookup text values in a column and display a list of corresponding names from another column?

    My spreadsheet looks like this:
                     Monday...
    Name 1      4PM
    Name 2      4PM
    Name 3      5PM
    Name 4      5PM
    Name 5      4PM
    I would like to create a spreadsheet that will display the values as follows:
    Openers (4PM)    Closers (5PM)
    Name 1                Name 3
    Name 2                Name 4
    Name 5
    Any help would be greatly appreciated. Thanks!

    Hi Shawn,
    I think this will do it for you:
    There's an auxiliary column in your data entry table. It counts the entries for each distinct time.
    The formula in the auxiliary column's body rows is:
    =COUNTIF(OFFSET(B$1, 0,0,ROW()), B)&"--"&B
    The formula in the Summary table's body rows is:
    =IFERROR(OFFSET(Schedule::$A$1, MATCH(ROW()-1&"--"&A$1, Schedule :: $C, 0)-1, 0), "")
    Regards,
    Jerry

  • HT4116 How do i get an iphoto library off my time machine back up and exported to a file of just photo images?

    I have backed up my imac that died, but how do i get the photos that are in time machine on the back up disc exported to another mac i have that also has an iphoto librbary?

    This should be of help in merging the libraries:  Fat Cat Software - iPhoto Library Manager Help - Merging libraries
    OT

  • Need a column based off a PL/SQL cursor, how to do this?

    Oracle9i Enterprise Edition Release 9.2.0.8.0 - 64bit Production
    With the Real Application Testing option
    JServer Release 9.2.0.8.0 - Production
    Report Builder 10.1.2.2.0
    ORACLE Server Release 10.1.0.5.0
    Oracle Procedure Builder 10.1.2.2.0
    Oracle ORACLE PL/SQL V10.1.0.5.0 - Production
    Oracle CORE     10.1.0.5.0     Production
    Hi,
    I am trying to create a fairly basic report but in the initial data model query, I have one column that is built based off of a PL/SQL cursor. How do I add this into my report? I have tried to create a function under Program Units and reference the function in my select statement for the data model however it keeps saying it is an invalid identifier, and I assume its looking in our database and not the function I created inside the report.
    This is what it looks like:
    SELECT   a.id,
             b.name,
             F_GET_GENERIC_NAME(b.code) "Generic Name",
             c.strength...and the function i want it to use in my report:
    FUNCTION F_GET_GENERIC_NAME (in_code varchar2) RETURN VARCHAR2 IS
    BEGIN
    DECLARE
    generic_name table.column%TYPE;
    CURSOR cs_get_generic_name IS
    SELECT /*+ USE_HASH (AR) */ desc
    FROM  a_ref AR, ai_ic AC    
    WHERE AC.code = in_code
    AND   AC.code = AR.code
    ORDER BY sort_nbr;
    BEGIN
           generic_name := '';
              FOR v_get_generic_name IN cs_get_generic_name
              LOOP
                 generic_name := generic_name || RTRIM(v_get_generic_name.desc)
                                     || '/' || ' ';
              END LOOP;
              generic_name := SUBSTR(generic_name, 1,(NVL(LENGTH(generic_name), 0) - 2));
    RETURN generic_name;
    END;
    END;
        Any suggestions? Should I just create the function in the database?

    I am trying to do it through a formula column but am encountering the following problem.
    I've created a formula column in my data model where I want the column to be (inside the group).
    Inside the PL/SQL for the column I reference the function that I had previously created with the following:
    function CF_Generic_nameFormula return Char is
    begin
         F_GET_GENERIC_NAME(:code);
    end;However it won't let me compile, giving the error that "F_GET_GENERIC_NAME is not a procedure or is undefined." Is there something else that I am missing?
    EDIT: Nevermind, i missed something simple like putting a return in front of the function call.
    Edited by: a small rabbit on Nov 3, 2009 10:43 AM
    Edited by: a small rabbit on Nov 3, 2009 10:44 AM

  • Count MySQL rows based off Value in Dynamic Table

    Greetings all. I have 2 MySQL tables; 1 that contains the names of my classes.(Class A, Class, B, etc.) and 1 table that contains the names of students in each Class (for example Class A: John Doe; Class A: Susie Smith.; Class B: Jane Doe). In the 2nd table the Class name is in its own column and the student's name is in a 2nd column.
    I currently have a dynamic repeating table that lists the names of all of the classes from the 1st table. What I'm trying to do is add a second column to this repeating dynamic table that lists the number of students in each class. For example; Row 1 of the dynamic table would say "Class A | 5; Class B | 3; Class C | 7, etc.). The dynamic table works perfectly to list the class names. For the life of me I can't figure out how to perform a count for each class to insert in the repeating table. I will be adding more Classes which as why I'm trying to set up the counting query dynamically. So far I have only been able to figure out how to count the total rows in the 2nd table, or count the rows with a specified class name. Any advice or guidance on how to count the number of rows in the 2nd MySQL table based off the class name in the repeating table is much appreciated. Thank you for any and all help. Have a great day.

    Select count(*), Class from MyTable
    Group by Class
    Time to learn about SQL:
    http://www.w3schools.com/sql/sql_intro.asp

  • Sub Query selection based on parameter value selected

    I have a parameter, and based on the value selected, I want to run one of two queries. I thought I could do either an IF THEN ELSE, or a CASE, but neither seem to be working.
    What I'm trying to do is this:
    IF parameter_value = 338 THEN
    (RUN THIS SELECT QUERY)
    ELSE
    (RUN THIS SELECT QUERY)
    END IF
    or
    SELECT CASE WHEN parameter_value = 338 THEN (RUN THIS SELECT QUERY)
    ELSE (RUN THIS SELECT QUERY)
    END X
    I'm getting errors with both. For the CASE statement, it says "too many values". For the IF statement, it just says "invalid SQL statement".
    Any suggestions would be appreciated.
    Thanks.

    Looks like this is what you want
    SQL> WITH T
      2       AS (SELECT LEVEL col
      3             FROM DUAL
      4           CONNECT BY LEVEL <= 5)
      5  SELECT *
      6    FROM T;
           COL
             1
             2
             3
             4
             5
    SQL>
    SQL> VARIABLE parameter_value    NUMBER
    SQL> EXEC    :parameter_value := 338;
    PL/SQL procedure successfully completed.
    SQL>
    SQL> WITH T
      2       AS (SELECT LEVEL col
      3             FROM DUAL
      4           CONNECT BY LEVEL <= 5)
      5  SELECT col
      6    FROM T
      7   WHERE col = DECODE (:parameter_value, 338, col, :parameter_value);  --- If 338 then select all if not 338 select only the one with parameter_value.
           COL
             1
             2
             3
             4
             5
    SQL>
    SQL> EXEC :parameter_value := 2;
    PL/SQL procedure successfully completed.
    SQL>
    SQL> WITH T
      2       AS (SELECT LEVEL col
      3             FROM DUAL
      4           CONNECT BY LEVEL <= 5)
      5  SELECT col
      6    FROM T
      7   WHERE col = DECODE (:parameter_value, 338, col, :parameter_value);
           COL
             2
    SQL>
    SQL> EXEC :parameter_value := 3;
    PL/SQL procedure successfully completed.
    SQL>
    SQL> WITH T
      2       AS (SELECT LEVEL col
      3             FROM DUAL
      4           CONNECT BY LEVEL <= 5)
      5  SELECT col
      6    FROM T
      7   WHERE col = DECODE (:parameter_value, 338, col, :parameter_value);
           COL
             3
    SQL> You need to use following where clause in your query
    WHERE column_name = DECODE (parameter_value, 338, col, parameter_value); -- replace the column_name with name of the column you are comparing against.G.
    Edited by: G. on Mar 8, 2011 3:36 PM
    formatted and added comments

  • Performance operations based on Column values in SQL server 2008

    Hi ,
    I have a table which consist of following columns
    ID    Formula              
    Values                 
    DisplayValue
    1                    
    a*b/100       100*12/100    
          null
    2                    
    b*c/100       
    12*4/100              
    null
    I want to perform operation based on column "Values" and save data after operations in new column Name "Display Value" .i.e I want to get the below result . Can anyone please help.
    ID    Formula              
    Values                 
    DisplayValue
    1                    
    a*b/100       100*12/100    
          12
    2                    
    b*c/100       
    12*4/100             
    0.48
    Thanks for the help.
    Regards, Priti A

    Try this,
    create table #mytable (ID int,Formula varchar(10), [Values] varchar(10), DisplayValue decimal(10,4))
    insert into #mytable values(1 ,'a*b/100','100*12/100',null)
    insert into #mytable values(2 ,'b*c/100','12*4/100',null)
    declare @rowcount int=1
    while @rowcount <= (select max(id) from #mytable)
    begin
    declare @expression nvarchar(max)
    select @expression=[values] from #mytable where id = + @rowcount
    declare @sql nvarchar(max)
    set @sql = 'select @result = ' + @expression
    declare @result decimal(10,4)
    exec sp_executesql @sql, N'@result decimal(10,4) output', @result = @result out
    update #mytable set DisplayValue= @result where id = @rowcount
    set @rowcount=@rowcount+1
    end
    select * from #mytable
    Regards, RSingh

  • Query on DSO, KF value +/- based on flag value in DSO

    Hi Experts,
    I have a query on DSO and it is running fine.
    Current Query output :
    CHAR1 | CHAR2 | KF1
    1111       S            100
    1111       H            100
    I want to put + or - sign for KF based on value of CHAR 2 (Flag) in query output.
    So
    Desired Query output :
    CHAR1 | CHAR2 | KF1
    1111       S            -100
    1111       H             100
    I can Add CHAR3 in DSO and based on CHAR2 value CHAR3 will store +1 or -1. Add it can be used to get + or -Value of KF using CKF.
    But without doing it (CHAR3), can I do it directly at query level ?
    Regards,
    Vinod

    Try this:
    RKF1: KF restricted on S
    RKF2: KF restricted on H
    CKF: (-1)*RKF1 + RKF2
    This should give you what you are looking for.
    Regards,
    Gaurav

  • CAML Query to get specific item in folder based on dropdown value using Javascript client object model

    Hi,
    I am using the Javascript Client object model.
    I have a custom list and a custom document library.
    Custom list contains 2 columns - dlName , dlValue
    The document library contains 2 folders - "folder1" ,  "folder2" and contains some images.
    The image name starts with the "dlValue" available in the custom list
    I am using a visual webpart and using javascript client object model.
    I am trying to achieve the below functionality:
    1) Load a dropdown with the custom list.
    2) set the image based on the value in dropdown.
    I have achieved the first option, I have set the dropdown, but not sure how to query the folder and set the image.
    Below is the code i have used so far:
    //In Visual webpart
    <select id="ddlTest" >
    </select>
    <br/>
    <div id="PreviewLayer">
    <img id="imgPlaceHolder" runat="server" alt="Image" title="imgPlaceHolder" src=" " />
    </div>
    // In Javascript file
    function RenderHtmlOnSuccess() {
    var ddlTest = this.document.getElementById("ddlTest");
    ddlTest.options.length = 0;
    var enumerator = this.customListItems.getEnumerator();
    while (enumerator.moveNext()) {
    var currentItem = enumerator.get_current();
    var dropdownValue = currentItem.get_item("dlValue");
    ddlTest.options[ddlTest.options.length] = new Option(currentItem.get_item("dlName"), dropdownValue);
    setImage(dropdownValue); // Not sure how to query the folder and set the image based on value.
    // Also if dropdown value is changed, corresponding image should be shown
    How to query the folder and based on dropdown value, show the image? Also, how to handle the dropdown value change?
    Thanks

    Hi,
    Here are two links for your reference:
    Example of how to Get Files from a Folder using Ecmascript \ Javascript client object model in SharePoint 2010
    http://sharepointmantra.wordpress.com/2013/10/19/example-of-how-to-get-files-from-a-folder-using-ecmascript-javascript-client-object-model-in-sharepoint-2010/
    SP2010 JSOM Client Object Model: How to get all documents in libraries including all folders recursively
    http://sharepoint.stackexchange.com/questions/70185/sp2010-jsom-client-object-model-how-to-get-all-documents-in-libraries-including
    In SharePoint 2013, we can also use REST API to achieve it.
    http://msdn.microsoft.com/en-us/magazine/dn198245.aspx
    Thanks,
    Dennis Guo
    TechNet Community Support
    Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support, contact
    [email protected]
    Dennis Guo
    TechNet Community Support

Maybe you are looking for