Search Results

Search found 3403 results on 137 pages for 'monthly statements'.

Page 40/137 | < Previous Page | 36 37 38 39 40 41 42 43 44 45 46 47  | Next Page >

  • figuring out which field to look for a value in with SQL and perl

    - by Micah
    I'm not too good with SQL and I know there's probably a much more efficient way to accomplish what I'm doing here, so any help would be much appreciated. Thanks in advance for your input! I'm writing a short program for the local school high school. At this school, juniors and seniors who have driver's licenses and cars can opt to drive to school rather than ride the bus. Each driver is assigned exactly one space, and their DLN is used as the primary key of the driver's table. Makes, models, and colors of cars are stored in a separate cars table, related to the drivers table by the License plate number field. My idea is to have a single search box on the main GUI of the program where the school secretary can type in who/what she's looking for and pull up a list of results. Thing is, she could be typing a license plate number, a car color, make, and model, someone driver's name, some student driver's DLN, or a space number. As the programmer, I don't know what exactly she's looking for, so a couple of options come to mind for me to build to be certain I check everywhere for a match: 1) preform a couple of SELECT * FROM [tablename] SQL statements, one per table and cram the results into arrays in my program, then search across the arrays one element at a time with regex, looking for a matched pattern similar to the search term, and if I find one, add the entire record that had a match in it to a results array to display on screen at the end of the search. 2) take whatever she's looking for into the program as a scaler and prepare multiple select statements around it, such as SELECT * FROM DRIVERS WHERE DLN = $Search_Variable SELECT * FROM DRIVERS WHERE First_Name = $Search_Variable SELECT * FROM CARS WHERE LICENSE = $Search_Variable and so on for each attribute of each table, sticking the results into a results array to show on screen when the search is done. Is there a cleaner way to go about this lookup without having to make her specify exactly what she's looking for? Possibly some kind of SQL statement I've never seen before?

    Read the article

  • How to determine loading status of images not attached to the DOM

    - by Rookwood
    I am working on a bit of javascript to plot data on a <canvas. The data points are marked by one of several different (small) image files. I am attempting to have the plot method wait until all the images are loaded. My best attempt thus far is such: var icon = { left : { air : new Image(), bone : new Image(), }, right : { air: new Image(), bone : new Image(), }, }; icon.left.air.src = option.imgPath + 'left.air.png'; icon.right.air.src = option.imgPath + 'right.air.png'; icon.left.bone.src = option.imgPath + 'left.bone.png'; icon.right.bone.src = option.imgPath + 'right.bone.png'; function main() { Canvas.draw(); // Make sure our image icons are loaded before we try to plot $(icon.left.air).load(function() { $(icon.right.air).load(function() { $(icon.left.bone).load(function() { $(icon.right.bone).load(function() { Data.plot(); }); }); }); }); } This works as expected most of the time. On occasion, it will fail and no data will be plotted. Inserting several console.log() statements shows that the script will silently stop working through the series of .load() statements, though code that comes after will be executed. My questions are as follows: Am I approaching this the right way? Is there a way to attach an event to my icon object that will fire once all of the images inside are loaded? This is a jquery plugin, so obviously jquery-based solutions are just as acceptable as vanilla javascript.

    Read the article

  • Is there a definitive reference document for Ruby syntax?

    - by JSW
    I'm searching for a definitive document on Ruby syntax. I know about the definitive documents for the core API and standard library, but what about the syntax itself? For instance, such a document should cover: reserved words, string literals syntax, naming rules for variables/classes/modules, all the conditional statements and their permutations, and so forth. I know there are many books and tutorials, yes, but every one of them is essentially a tutorial, each one having a range of different depth and focus. They will all, by necessity of brevity and narrative flow, omit certain details of the language that the author deems insignificant. For instance, did you know that you can use a case statement without an initial case value, and it will then execute the first true when clause? Any given Ruby book or tutorial may or may not cover that particular lesser-known functionality of the case syntax. It's not discussed in the section in "Programming Ruby" about case statements. But that is just one small example. So far the best documentation I've found is the rubyspec project, which appears to be an attempt to write a complete test suite for the language. That's not bad, but it's a bit hard to use from a practical standpoint as a developer working on my own projects. Am I just missing something or is there really no definitive readable document defining the whole of Ruby syntax?

    Read the article

  • Selectively search and replace certain lines using a regular expression

    - by eneveu
    I have a file containing a lot of SQL statements, such as: CREATE TABLE "USER" ( "ID" INTEGER PRIMARY KEY, "NAME" CHARACTER VARYING(50) NOT NULL, "AGE" INTEGER NOT NULL ); COPY "USER" (id, name, age) FROM stdin; 1 Skywalker 19 2 Kenobi 57 I want the column names in the COPY statements to be uppercased and quoted: COPY "USER" ("ID", "NAME", "AGE") FROM stdin; Using sed, I found the following regexp: sed -r 's/([( ])(\w+)([,)])/\1"\U\2\E"\3/g' It does replace the column names, but it is not selective enough, and replaces other words in the file: ~/test]$sed -r 's/([( ])(\w+)([,)])/\1"\U\2\E"\3/g' star_wars_example CREATE TABLE "USER" ( "ID" INTEGER PRIMARY "KEY", "NAME" CHARACTER VARYING("50")NOT "NULL", "AGE" INTEGER NOT NULL ); COPY "USER" ("ID", "NAME", "AGE") FROM stdin; 1 Skywalker 19 2 Kenobi 57 To avoid this problem, I want sed to only apply my regexp to the lines starting with COPY and ending with FROM stdin;. I have looked into lookahead / lookbehind, but they are not supported in sed. They seem to be supported in super-sed, but I am currently using Cygwin (Windows is mandatory here...) and it does not seem available in the package list. Is there a way to force sed to only consider specific line? I've considered piping my file through grep before applying sed, but other lines will then disappear from the output. Am I missing something obvious? It would be great if the answer was easily applicable on a default Cygwin install. I guess I could try installing super-sed on cygwin, but I'd like to know if there are more obvious ideas

    Read the article

  • NHibernate will not insert a record

    - by Brian Beckham
    I have an application that is now 4+ years old that is exhibiting some odd behavior on our latest deployment. The application uses nHibernate for all inserts / updates / selects, etc. We are currently using .NET 2.0, and nHibernate 1.2 (I know, we need to upgrade) This deployment is on Windows 2008 Server x64, IIS 7.5 - what I have seen so far is that the application runs, but is unable to insert or update records in the DB - reads seem fine so far, but writes are a problem. SOME writes actually work, inserts into some small tables, but most never even make it to the DB. Using SQL Profiler, the insert / updates never make it to the server, and turning log4net up to DEBUG, and show_sql true - the select statements appear, but the insert / update statements never make it into the log at all, and never show up at the server. What's even more odd is that the application seems to be oblivious to this - the commandandclose runs without exception (open session in view with an httpmodule), the domain objects come back with uuid's generated, etc. but never get persisted. Certainly an upgrade is due, but I would hate to try it during a deployment, and without time to accurately test the app. Any ideas?

    Read the article

  • In Emacs, how can I use imenu more sensibly with C#?

    - by Cheeso
    I've used emacs for a long time, but I haven't been keeping up with a bunch of features. One of these is speedbar, which I just briefly investigated now. Another is imenu. Both of these were mentioned in in-emacs-how-can-i-jump-between-functions-in-the-current-file? Using imenu, I can jump to particular methods in the module I'm working in. But there is a parse hierarchy that I have to negotiate before I get the option to choose (with autocomplete) the method name. It goes like this. I type M-x imenu and then I get to choose Using or Types. The Using choice allows me to jump to any of the using statements at the top level of the C# file (something like imports statements in a Java module, for those of you who don't know C#). Not super helpful. I choose Types. Then I have to choose a namespace and a class, even though there is just one of each in the source module. At that point I can choose between variables, types, and methods. If I choose methods I finally get the list of methods to choose from. The hierarchy I traverse looks like this; Using Types Namespace Class Types Variables Methods method names Only after I get to the 5th level do I get to select the thing I really want to jump to: a particular method. Imenu seems intelligent about the source module, but kind of hard to use. Am I doing it wrong?

    Read the article

  • row number over text column sort

    - by Marty Trenouth
    I'm having problems with dynamic sorting using ROW Number in SQL Server. I have it working but it's throwing errors on non numeric fields. What do I need to change to get sorts with Alpha Working??? ID Description 5 Test 6 Desert 3 A evil Ive got a Sql Prodcedure CREATE PROCEDURE [CRUDS].[MyTable_Search] -- Add the parameters for the stored procedure here -- Full Parameter List @ID int = NULL, @Description nvarchar(256) = NULL, @StartIndex int = 0, @Count int = null, @Order varchar(128) = 'ID asc' AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; -- Insert statements for procedure here Select * from ( Select ROW_NUMBER() OVER (Order By case when @Order = 'ID asc' then [TableName].ID when @Order = 'Description asc' then [TableName].Description end asc, case when @Order = 'ID desc' then [TableName].ID when @Order = 'Description desc' then [TableName].Description end desc ) as row, [TableName].* from [TableName] where (@ID IS NULL OR [TableName].ID = @ID) AND (@Description IS NULL OR [TableName].Description = @Description) ) as a where row > @StartIndex and (@Count is null or row <= @StartIndex + @Count) order by case when @Order = 'ID asc' then a.ID when @Order = 'Description asc' then a.Description end asc, case when @Order = 'ID desc' then a.ID when @Order = 'Description desc' then a.Description end desc END

    Read the article

  • Sql Server 2005 multiple insert with c#

    - by bottlenecked
    Hello. I have a class named Entry declared like this: class Entry{ string Id {get;set;} string Name {get;set;} } and then a method that will accept multiple such Entry objects for insertion into the database using ADO.NET: static void InsertEntries(IEnumerable<Entry> entries){ //build a SqlCommand object using(SqlCommand cmd = new SqlCommand()){ ... const string refcmdText = "INSERT INTO Entries (id, name) VALUES (@id{0},@name{0});"; int count = 0; string query = string.Empty; //build a large query foreach(var entry in entries){ query += string.Format(refcmdText, count); cmd.Parameters.AddWithValue(string.Format("@id{0}",count), entry.Id); cmd.Parameters.AddWithValue(string.Format("@name{0}",count), entry.Name); count++; } cmd.CommandText=query; //and then execute the command ... } } And my question is this: should I keep using the above way of sending multiple insert statements (build a giant string of insert statements and their parameters and send it over the network), or should I keep an open connection and send a single insert statement for each Entry like this: using(SqlCommand cmd = new SqlCommand(){ using(SqlConnection conn = new SqlConnection(){ //assign connection string and open connection ... cmd.Connection = conn; foreach(var entry in entries){ cmd.CommandText= "INSERT INTO Entries (id, name) VALUES (@id,@name);"; cmd.Parameters.AddWithValue("@id", entry.Id); cmd.Parameters.AddWithValue("@name", entry.Name); cmd.ExecuteNonQuery(); } } } What do you think? Will there be a performance difference in the Sql Server between the two? Are there any other consequences I should be aware of? Thank you for your time!

    Read the article

  • Need help extrapolating Java code

    - by Berlioz
    If anyone familiar with Rebecca Wirfs-Brock, she has a piece of Java code found in her book titled, Object Design: Roles, Responsibilities, and Collaborations. Here is the quote Applying Double Dispatch to a Specific Problem To implement the game Rock, Paper, Scissors we need to write code that determines whether one object “beats” another. The game has nine possible outcomes based on the three kinds of objects. The number of interactions is the cross product of the kinds of objects. Case or switch statements are often governed by the type of data that is being operated on. The object-oriented language equivalent is to base its actions on the class of some other object. In Java, it looks like this Here is the piece of Java code on page 16 ' import java.util.*; import java.lang.*; public class Rock { public static void main(String args[]) { } public static boolean beats(GameObject object) { if (object.getClass.getName().equals("Rock")) { result = false; } else if (object.getClass.getName().equals("Paper")) { result = false; } else if(object.getClass.getName().equals("Scissors")) { result = true; } return result; } }' ===This is not a very good solution. First, the receiver needs to know too much about the argument. Second, there is one of these nested conditional statements in each of the three classes. If new kinds of objects could be added to the game, each of the three classes would have to be modified. Can anyone share with me how to get this "less than optimal" piece of code to work in order to see it 'working'. She proceeds to demonstrate a better way, but I will spare you. Thanks

    Read the article

  • Cost of logic in a query

    - by FrustratedWithFormsDesigner
    I have a query that looks something like this: select xmlelement("rootNode", (case when XH.ID is not null then xmlelement("xhID", XH.ID) else xmlelement("xhID", xmlattributes('true' AS "xsi:nil"), XH.ID) end), (case when XH.SER_NUM is not null then xmlelement("serialNumber", XH.SER_NUM) else xmlelement("serialNumber", xmlattributes('true' AS "xsi:nil"), XH.SER_NUM) end), /*repeat this pattern for many more columns from the same table...*/ FROM XH WHERE XH.ID = 'SOMETHINGOROTHER' It's ugly and I don't like it, and it is also the slowest executing query (there are others of similar form, but much smaller and they aren't causing any major problems - yet). Maintenance is relatively easy as this is mostly a generated query, but my concern now is for performance. I am wondering how much of an overhead there is for all of these case expressions. To see if there was any difference, I wrote another version of this query as: select xmlelement("rootNode", xmlforest(XH.ID, XH.SER_NUM,... (I know that this query does not produce exactly the same, thing, my plan was to move the logic to PL/SQL or XSL) I tried to get execution plans for both versions, but they are the same. I'm guessing that the logic does not get factored into the execution plan. My gut tells me the second version should execute faster, but I'd like some way to prove that (other than writing a PL/SQL test function with timing statements before and after the query and running that code over and over again to get a test sample). Is it possible to get a good idea of how much the case-when will cost? Also, I could write the case-when using the decode function instead. Would that perform better (than case-statements)?

    Read the article

  • jQuery class selector oddness

    - by x3sphere
    I'm using jQuery to change the background image of a button depending on the class associated with it on hover. It only works if I put the hover statements in separate functions, however. Why is this? Here's the NON working code, always evaluates to the .submit hover statement, even when that class is removed via the keyup event. $(function() { { $('.submit-getinfo').hover(function () { $(this).css( {backgroundPosition: "right bottom"} ); }, function() { $(this).css( {backgroundPosition: "right top"} ); //$(this).removeClass('submithover'); }); $('.submit').hover(function () { $(this).css( {backgroundPosition: "left bottom"} ); }, function() { $(this).css( {backgroundPosition: "left top"} ); //$(this).removeClass('submithover'); }); }}); Working code: $(function() { { $('.submit').hover(function () { $(this).css( {backgroundPosition: "left bottom"} ); }, function() { $(this).css( {backgroundPosition: "left top"} ); //$(this).removeClass('submithover'); }); }}); $('#test').bind('keyup', function() { if (url == 'devel') { $("#submit").addClass("submit-getinfo").removeClass("submit"); $('.submit-getinfo').hover(function () { $(this).css( {backgroundPosition: "right bottom"} ); }, function() { $(this).css( {backgroundPosition: "right top"} ); //$(this).removeClass('submithover'); }); } } ); I just fail to see why I have to put the hover statements in separate functions, instead of sticking both in the main DOM.

    Read the article

  • MSSQL 2008 - Bit Param Evaluation alters Execution Plan

    - by Nathanial Woolls
    I have been working on migrating some of our data from Microsoft SQL Server 2000 to 2008. Among the usual hiccups and whatnot, I’ve run across something strange. Linked below is a SQL query that returns very quickly under 2000, but takes 20 minutes under 2008. I have read quite a bit on upgrading SQL server and went down the usual paths of checking indexes, statistics, etc. before coming to the conclusion that the following statement, found in the WHERE clause, causes the execution plan for the steps that follow this statement to change dramatically: And ( @bOnlyUnmatched = 0 -- offending line Or Not Exists( The SQL statements and execution plans are linked below. A coworker was able to rewrite a portion of the WHERE clause using a CASE statement, which seems to “trick” the optimizer into using a better execution plan. The version with the CASE statement is also contained in the linked archive. I’d like to see if someone has an explanation as to why this is happening and if there may be a more elegant solution than using a CASE statement. While we can work around this specific issue, I’d like to have a broader understanding of what is happening to ensure the rest of the migration is as painless as possible. Zip file with SQL statements and XML execution plans Thanks in advance!

    Read the article

  • ProgressDialog won't show, even in onPreExecute of AsyncTask

    - by Geltrude
    In my class, Main extends Activity, I've this: @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case ... case CREDENTIAL_VIEW: new SetStatusProgressBar(this).execute(); And there is this nested class: private class SetStatusProgressBar extends AsyncTask<String, Void, Boolean> { private ProgressDialog dialog; private Main ctx; public SetStatusProgressBar(Main ctx) { this.ctx = ctx; dialog = new ProgressDialog(ctx); } // progress dialog to show user that contacting server. protected void onPreExecute() { this.dialog = ProgressDialog.show(ctx, null, "Refreshing data from server...", true, false); } @Override protected void onPostExecute(final Boolean success) { //... //statements that refresh UI //... if (dialog.isShowing()) { dialog.dismiss(); timerProgressBarStop(); } } protected Boolean doInBackground(final String... args) { //... //statements to download data from server //... return true; } } In the Main class I open a second Activity, in this way: Intent myIntent = new Intent(Main.this, Credentials.class); startActivityForResult(myIntent, CREDENTIAL_VIEW); That second Activity returns to the Main activity in this way: Intent intent = new Intent(); setResult(RESULT_OK, intent); finish(); I don't understand why when I navigate from the second Activity to the Main, the ProgressDialog will show ONLY AFTER that the UI refreshes... In this way the Progress Dialog stays on the screen only for half second... and then hides! :( I'd like to see the ProgressDialog on top during all the download time! Help, please. Thank you all

    Read the article

  • Printing the "source" class in a log statement with a log4j wrapper

    - by Dur4ndal
    My application has a homebrew logging class that I'm migrating to using log4j under the covers. However, since I'm using the homebrew class to pass the rest of the application's logging statements to log4j, the output statements are logged as coming from the wrapper class instead of the source class. Is there a way to ensure that the "correct" source is being shown besides creating new org.apache.log4j.Logger instances for every log statement? I've also tried using the Logger.log(String callerFQCN, Priority level, Object message, Throwable t) method, but it doesnt seem to be working, for example: public class Logger2 { public static org.apache.log4j.Logger log4JLogger = org.apache.log4j.Logger.getLogger(Logger2.class); public static void warning(Object source, String message) { log(source, message, Level.WARN, null) } private static void log(Object source, String message, Level level, Throwable t) { String className = source.getClass().getName(); System.out.println("Logging class should be " + className); log4JLogger.log(className, loggingLevel, message, t); } } When called by: public void testWarning() { Logger2.warning(new Integer(3), "This should warn"); } Prints: Logging class should be java.lang.Integer 2010-05-25 10:49:57,152 WARN test.Logger2 - This should warn

    Read the article

  • TextBox change is not saved to DataTable

    - by SeaDrive
    I'm having trouble with a simple table edit in a Winform application. I must have missed a step. I have a DataSet containing a DataTable connected to a database with a SqlDataAdapter. There is a SqlCommandBuilder on the SqlDataAdapter. On the form, there are TextBoxes which are bound to the DataTable. The binding was done in the Designer and it machine-produced statements like this: this.tbLast.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.belkData, "belk_mem.last", true)); When I fill the row in the DataTable, the values from the database appear in the textboxes, but when I change contents of the TextBox, the changes are apparently not being going to the DataTable. When I try to save change both of the following return null: DataTable dtChanges = dtMem.GetChanges(); DataSet dsChanges = belkData.GetChanges(); What did I forget? Edit - response to mrlucmorin: The save is under a button. Code is: BindingContext[belkData, "belk_mem"].EndCurrentEdit(); try { DataSet dsChanges = belkData.GetChanges(); if (dsChanges != null) { int nRows = sdaMem.Update(dsChanges); MessageBox.Show("Row(s) Updated: " + nRows.ToString()); belkData.AcceptChanges(); } else { MessageBox.Show("Nothing to save.", "No changes"); } } catch (Exception ex) { MessageBox.Show("Error: " + ex.Message); } I've tried putting in these statements without any change in behavior: dtMem.AcceptChanges(); belkData.AcceptChanges();

    Read the article

  • C++: Case statement within while loop?

    - by Jason
    I just started C++ but have some prior knowledge to other languages (vb awhile back unfortunately), but have an odd predicament. I disliked using so many IF statements and wanted to use switch/cases as it seemed cleaner, and I wanted to get in the practice.. But.. Lets say I have the following scenario (theorietical code): while(1) { //Loop can be conditional or 1, I use it alot, for example in my game char something; std::cout << "Enter something\n -->"; std::cin >> something; //Switch to read "something" switch(something) { case 'a': cout << "You entered A, which is correct"; break; case 'b': cout << "..."; break; } } And that's my problem. Lets say I wanted to exit the WHILE loop, It'd require two break statements? This obviously looks wrong: case 'a': cout << "You entered A, which is correct"; break; break; So can I only do an IF statement on the 'a' to use break;? Am I missing something really simple? This would solve a lot of my problems that I have right now.

    Read the article

  • Which Java debugger do *you* use.

    - by mikevdg
    I spend a lot of time debugging applications in Eclipse using JPDA. There are a few issues with the Eclipse debugger which really annoy me. Can anybody recommend plug-ins, better debuggers or perhaps tricks that I don't know of yet? In the "Variables" tab, you can type in and execute bits of Java code. However, you first need to click on something (I usually click on "this") to give it some context. Then, after you've typed in a lengthy Java expression to debug something and "execute" it, your expression gets replaced with the result, so you need to type it in all over again. Is there some better way, such as a console or something that I'm missing? When you're poking through data structures, the presentation in the debugger leaves much to be desired. You see the internal representation of Lists, Maps, StringBuilders etc. What I want to see is what these objects conceptually contain. Is there a way of doing this, perhaps using some other debugger, or an extension or something? When an Exception is thrown, is there some way of inspecting the state of the application where the Exception was thrown? Currently I need to set breakpoints just before the Exception occurs and then try to reproduce it. When I'm stepping over a line with many statements on it, I can't actually see which of those statements is being executed, except by "stepping in" to each one to see where it takes me. If no source code is found, Eclipse just stares blankly at you. You get a helpful screen saying "Class File Editor / Source code not found" which is completely useless. I'd much prefer to be able to step through the bytecodes so I can at least see what is going on. Does anybody know of a Java debugger that does this better than Eclipse?

    Read the article

  • How to efficiently use LOCK_ESCALATION mssql 2008

    - by Avias
    I'm currently having troubles with frequent deadlocks with a specific user table in MS SQL 2008. Here are some facts about this particular table: Has a large amount of rows (1 to 2 million) All the indexes used on this table only has "use row lock" ticked on its option rows are frequently updated by multiple transactions but are unique (e.g. probably a thousand or more update statements are executed to different unique rows every hour) the table does not use partitions. Upon checking the table on sys.tables, I found that the lock_escalation is set to TABLE I'm very tempted to turn the lock_escalation for this table to DISABLE but I'm not really sure what side effect this would incur. From What I understand, using DISABLE will minimize escalating locks to TABLE level which if combined with the row lock settings of the indexes should theoretically minimize the deadlocks I am encountering.. From what I have read in Determining threshold for lock escalation it seems that locking automatically escalates when a single transaction fetches 5000 rows.. What does a single transaction mean in this sense? A single session/connection getting 5000 rows thru individual update/select statements? Or is it a single sql update/select statement that fetches 5000 or more rows? Any insight is appreciated, btw, n00b DBA here Thanks

    Read the article

  • Dynamic Data Extract Tools

    - by Kevin McGovern
    I've been searching around for a few weeks now for a tool that either is fully built or a direction of something I could build for dynamically extracting data via a web interface. Basically, what I'm looking for is a way to give users a list of all available data objects from our database and then let them pick ones from the list they'd like to view and set parameters then export the results to an excel file. Right now we're doing it purely with SQL statements but we have hundreds of objects so as you might imagine, those statements are really complex and prone to errors. It would be great if there was a tool available to do this or if someone had an idea of an easy way to organize this. Any help would be greatly appreciated. We've looked at BI tools like QlikView and Tableau but that is probably overkill for what we're trying to do. The open-source BI tools we've looked at seemed really primitive in their functionality. The other thing we looked at was MSAS (our DB is SQL Server) but I'd prefer something that was more database-agnostic and lived on a web server instead of on the database.

    Read the article

  • C++: Switch statement within while loop?

    - by Jason
    I just started C++ but have some prior knowledge to other languages (vb awhile back unfortunately), but have an odd predicament. I disliked using so many IF statements and wanted to use switch/cases as it seemed cleaner, and I wanted to get in the practice.. But.. Lets say I have the following scenario (theorietical code): while(1) { //Loop can be conditional or 1, I use it alot, for example in my game char something; std::cout << "Enter something\n -->"; std::cin >> something; //Switch to read "something" switch(something) { case 'a': cout << "You entered A, which is correct"; break; case 'b': cout << "..."; break; } } And that's my problem. Lets say I wanted to exit the WHILE loop, It'd require two break statements? This obviously looks wrong: case 'a': cout << "You entered A, which is correct"; break; break; So can I only do an IF statement on the 'a' to use break;? Am I missing something really simple? This would solve a lot of my problems that I have right now.

    Read the article

  • SQLite3 database doesn't actually insert data - iPhone

    - by user334934
    I'm trying to add a new entry into my database, but it's not working. There are no errors thrown, and the code that is supposed to be executed after the insertion runs, meaning there are no errors with the query. But still, nothing is added to the database. I've tried both prepared statements and the simpler sqlite3_exec and it's the same result. I know my database is being loaded because the info for the tableview (and subsequent tableviews) are loaded from the database. The connection isn't the problem. Also, the log of the sqlite3_last_insert_rowid(db) returns the correct number for the next row. But still, the information is not saved. Here's my code: db = [Database openDatabase]; NSString *query = [NSString stringWithFormat:@"INSERT INTO lists (name) VALUES('%@')", newField.text]; NSLog(@"Query: %@",query); sqlite3_stmt *statement; if (sqlite3_prepare_v2(db, [query UTF8String], -1, &statement, nil) == SQLITE_OK) { if(sqlite3_step(statement) == SQLITE_DONE){ NSLog(@"You created a new list!"); int newListId = sqlite3_last_insert_rowid(db); MyList *newList = [[MyList alloc] initWithName:newField.text idNumber:[NSNumber numberWithInt:newListId]]; [self.listArray addObject:newList]; [newList release]; [self.tableView reloadData]; sqlite3_finalize(statement); } else { NSAssert1(0, @"Error while inserting data. '%s'", sqlite3_errmsg(db)); } } [Database closeDatabase:db]; Again, no errors have been thrown. The prepare and step statements return SQLITE_OK and SQLITE_DONE respectively, yet nothing happens. Any help is appreciated!

    Read the article

  • Why is this removing all elements from my LinkedList?

    - by Brian
    Why is my remove method removing every element from my Doubly Linked List? If I take out that if/else statements then I can successfully remove middle elements, but elements at the head or tail of the list still remain. However, I added the if/else statements to take care of elements at the head and tail, unfortunately this method now removes every element in my list. What am I do wrong? public void remove(int n) { LinkEntry<E> remove_this = new LinkEntry<E>(); //if nothing comes before remove_this, set the head to equal the element after remove_this if (remove_this.previous == null) head = remove_this.next; //otherwise set the element before remove_this equal to the element after remove_this else remove_this.previous.next = remove_this.next; //if nothing comes after remove_this, set the tail equal to the element before remove_this if (remove_this.next == null) tail = remove_this.previous; //otherwise set the next element's previous pointer to the element before remove_this else remove_this.next.previous = remove_this.previous; //if remove_this is located in the middle of the list, enter this loop until it is //found, then remove it, closing the gap afterwards. int i = 0; for (remove_this = head; remove_this != null; remove_this = remove_this.next) { //if i == n, stop and delete 'remove_this' from the list if (i == n) { //set the previous element's next to the element that comes after remove_this remove_this.previous.next = remove_this.next; //set the element after remove_this' previous pointer to the element before remove_this remove_this.next.previous = remove_this.previous; break; } //if i != n, keep iterating through the list i++; } }

    Read the article

  • Building KPIs to monitor your business Its not really about the Technology

    When I have discussions with people about Business Intelligence, one of the questions the inevitably come up is about building KPIs and how to accomplish that. From a technical level the concept of a KPI is very simple, almost too simple in that it is like the tip of an iceberg floating above the water. The key to that iceberg is not really the tip, but the mass of the iceberg that is hidden beneath the surface upon which the tip sits. The analogy of the iceberg is not meant to indicate that the foundation of the KPI is overly difficult or complex. The disparity in size in meant to indicate that the larger thing that needs to be defined is not the technical tip, but the underlying business definition of what the KPI means. From a technical perspective the KPI consists of primarily the following items: Actual Value This is the actual value data point that is being measured. An example would be something like the amount of sales. Target Value This is the target goal for the KPI. This is a number that can be measured against Actual Value. An example would be $10,000 in monthly sales. Target Indicator Range This is the definition of ranges that define what type of indicator the user will see comparing the Actual Value to the Target Value. Most often this is defined by stoplight, but can be any indicator that is going to show a status in a quick fashion to the user. Typically this would be something like: Red Light = Actual Value more than 5% below target; Yellow Light = Within 5% of target either direction; Green Light = More than 5% higher than Target Value Status\Trend Indicator This is an optional attribute of a KPI that is typically used to show some kind of trend. The vast majority of these indicators are used to show some type of progress against a previous period. As an example, the status indicator might be used to show how the monthly sales compare to last month. With this type of indicator there needs to be not only a definition of what the ranges are for your status indictor, but then also what value the number needs to be compared against. So now we have an idea of what data points a KPI consists of from a technical perspective lets talk a bit about tools. As you can see technically there is not a whole lot to them and the choice of technology is not as important as the definition of the KPIs, which we will get to in a minute. There are many different types of tools in the Microsoft BI stack that you can use to expose your KPI to the business. These include Performance Point, SharePoint, Excel, and SQL Reporting Services. There are pluses and minuses to each technology and the right technology is based a lot on your goals and how you want to deliver the information to the users. Additionally, there are other non-Microsoft tools that can be used to expose KPI indicators to your business users. Regardless of the technology used as your front end, the heavy lifting of KPI is in the business definition of the values and benchmarks for that KPI. The discussion about KPIs is very dependent on the history of an organization and how much they are exposed to the attributes of a KPI. Often times when discussing KPIs with a business contact who has not been exposed to KPIs the discussion tends to also be a session educating the business user about what a KPI is and what goes into the definition of a KPI. The majority of times the business user has an idea of what their actual values are and they have been tracking those numbers for some time, generally in Excel and all manually. So they will know the amount of sales last month along with sales two years ago in the same month. Where the conversation tends to get stuck is when you start discussing what the target value should be. The actual value is answering the What and How much questions. When you are talking about the Target values you are asking the question Is this number good or bad. Typically, the user will know whether or not the value is good or bad, but most of the time they are not able to quantify what is good or bad. Their response is usually something like I just know. Because they have been watching the sales quantity for years now, they can tell you that a 5% decrease in sales this month might actually be a good thing, maybe because the salespeople are all waiting until next month when the new versions come out. It can sometimes be very hard to break the business people of this habit. One of the fears generally is that the status indicator is not subjective. Thus, in the scenario above, the business user is going to be fearful that their boss, just looking at a negative red indicator, is going to haul them out to the woodshed for a bad month. But, on the flip side, if all you are displaying is the amount of sales, only a person with knowledge of last month sales and the target amount for this month would have any idea if $10,000 in sales is good or not. Here is where a key point about KPIs needs to be communicated to both the business user and any user who might be viewing the results of that KPI. The KPI is just one tool that is used to report on business performance. The KPI is meant as a quick indicator of one business statistic. It is not meant to tell the entire story. It does not answer the question Why. Its primary purpose is to objectively and quickly expose an area of the business that might warrant more review. There is always going to be the need to do further analysis on any potential negative or neutral KPI. So, hopefully, once you have convinced your business user to come up with some target numbers and ranges for status indicators, you then need to take the next step and help them answer the Why question. The main question here to ask is, Okay, you see the indicator and you need to discover why the number is what is, where do you go?. The answer is usually a combination of sources. A sales manager might have some of the following items at their disposal (Marketing report showing a decrease in the promotional discounts for the month, Pricing Report showing the reduction of prices of older models, an Inventory Report showing the discontinuation of a particular product line, or a memo showing the ending of a large affiliate partnership. The answers to the question Why are never as simple as a single indicator value. Bring able to quickly get to this information is all about designing how a user accesses the KPIs and then also how easily they can get to the additional information they need. This is where a Dashboard mentality can come in handy. For example, the business user can have a dashboard that shows their KPIs, but also has links to some of the common reports that they run regarding Sales Data. The users boss may have the same KPIs on their dashboard, but instead of links to individual reports they are going to have a link to a status report that was created by the user that pulls together all the data about the KPI in a summary format the users boss can review. So some of the key things to think about when building or evaluating KPIs for your organization: Technology should not be the driving factor KPIs are of little value without some indicator for whether a value is good, bad or neutral. KPIs only give an answer to the Is this number good\bad? question Make sure the ability to drill into the Why of a KPI is close at hand and relevant to the user who is viewing the KPI. The KPI is a key business tool when defined properly to help monitor business performance across the enterprise in an objective and consistent manner. At times it might feel like the process of defining the business aspects of a KPI can sometimes be arduous, the payoff in the end can far outweigh the costs. Some of the benefits of going through this process are a better understanding of the key metrics for an organization and the measure of those metrics and a consistent snapshot of business performance that can be utilized across the organization. And I think that these are benefits to any organization regardless of the technology or the implementation.Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • Communities - The importance of exchange and discussion

    Communication with your environment is an essential part of everyone's life. And it doesn't matter whether you are actually living in a rural area in the middle of nowhere, within the pulsating heart of a big city, or in my case on a wonderful island in the Indian Ocean. The ability to exchange your thoughts, your experience and your worries with another person helps you to get different points of view and new ideas on how to resolve an issue you might be confronted with. Benefits of community work What happens to be common sense in your daily life, also applies to your work environment. Working in IT, or ICT as it is called in Mauritius, requires a lot of reading and learning. Not only during your lectures at the university but with your colleagues in a project assignment and hopefully with 'unknown' pals in the universe of online communities. At least I can say that I learned quite a lot from other developers code, their responses in various forums, their numerous blog articles, and while attending local user group meetings. When I started to work as a professional software developer (or engineer some may say) years ago I immediately checked the existence of communities on the programming language, the database technology and other vital information on software development in general. Luckily, it wasn't too difficult to find. My employer had a subscription of the monthly magazines and newsletters of a national organisation which also run the biggest forum in that area. Getting in touch with other developers and reading their common problems but also solutions was a huge benefit to my growth. Image courtesy of Michael Kappel (CC BY-NC 2.0) Active participation and regular contribution to this community gave me some nice advantages, too. Within three years I was listed as a conference speaker at the annual developer's conference and provided several sessions on different topics during consecutive years. Back in 2004, I took over the responsibility and management of the monthly meetings of a regional user group, and organised it for more than two years. Furthermore, I was invited to the newly-founded community program of Microsoft Germany (Community Leader/Insider Program - CLIP). My website on Active FoxPro Pages was nominated in the second batch of online communities. Due to my community work and providing advice to others, I had the honour to be awarded as Microsoft Most Valuable Professional (MVP) - Visual Developer for Visual FoxPro in the years 2006 and 2007. It was a great experience to meet with other like-minded people and I'm really grateful for that. Just in case, more details are listed in my Curriculum Vitae. But this all changed when I moved to Mauritius... Cyber island Mauritius? During the first months in Mauritius I was way too busy to think about community activities at all. First of all, there was the new company that had to be set up, the new staff had to be trained and of course the communication work-flows and so on with the project managers back in Germany had to be sorted out, too. Second, I had to get a grip of my private matters like getting the basics for my new household or exploring the neighbourhood, and last but not least I needed a break from the hectic and intensive work prior to my departure. As soon as the sea literally calmed down, I started to have conversations with my colleagues about communities and user groups. Sadly, it turned out that there were none, or at least no one was aware of any at that time. Oh oh, what did I do? Anyway, having this kind of background and very positive experience with off-line and on-line activities I decided for myself that some day I'm going to found a community in Mauritius for all kind of IT/ICT-related fields. The main focus might be on software development but not on a certain technology or methodology. It was clear to me that it should be an open infrastructure and anyone is welcome to join, to experience, to share and to contribute if they would like to. That was the idea at that time... Ok, fast-forward to recent events. At the end of October 2012 I was invited to an event called Open Days organised by Microsoft Indian Ocean Islands together with other local partners and resellers. There I got in touch with local Technical Evangelist Arnaud Meslier and we had a good conversation on communities during the breaks. Eventually, I left a good impression on him, as we are having chats on Facebook or Skype irregularly. Well, seeing that my personal and professional surroundings have been settled and running smooth, having that great exchange and contact with Microsoft IOI (again), and being really eager to re-animate my intentions from 2007, I recently founded a new community: Mauritius Software Craftsmanship Community - #MSCC It took me a while to settle down with the name but it was obvious that the community should not be attached to one single technology, like ie. .NET user group, Oracle developers, or Joomla friends (these are fictitious names). There are several other reasons why I came up with 'Craftsmanship' as the core topic of this community. The expression of 'engineering' didn't feel right with the fields covered. Software development in all kind of facets is a craft, and therefore demands a lot of practice but also guidance from more experienced developers. It also includes the process of designing, modelling and drafting the ideas. Has to deal with various types of tests and test methodologies, and of course should be focused on flexible and agile ways of acting. In order to meet and to excel a customer's request for a solution. Next, I was looking for an easy way to handle the organisation of events and meeting appointments. Using all kind of social media platforms like Google+, LinkedIn, Facebook, Xing, etc. I was never really confident about their features of event handling. More by chance I stumbled upon Meetup.com and in combination with the other entities (G+ Communities, FB Pages or in Groups) I am looking forward to advertise and manage all future activities here: Mauritius Software Craftsmanship Community This is a community for those who care and are proud of what they do. For those developers, regardless how experienced they are, who want to improve and master their craft. This is a community for those who believe that being average is just not good enough. I know, there are not many 'craftsmen' yet but it's a start... Let's see how it looks like by the end of the year. There are free smartphone apps for Android and iOS from Meetup.com that allow you to keep track of meetings and to stay informed on latest updates. And last but not least, there will be a Trello workspace to collect and share ideas and provide downloads of slides, etc. Sharing is caring! As mentioned, the #MSCC is present in various social media networks in order to cover as many people as possible here in Mauritius. Following is an overview of the current networks: Twitter - Latest updates and quickies Google+ - Community channel Facebook - Community Page LinkedIn - Community Group Trello - Collaboration workspace to share and develop ideas Hopefully, this covers the majority of computer-related people in Mauritius. Please spread the word about the #MSCC between your colleagues, your friends and other interested 'geeks'. Your future looks bright Running and participating in a user group or any kind of community usually provides quite a number of advantages for anyone. On the one side it is very joyful for me to organise appointments and get in touch with people that might be interested to present a little demo of their projects or their recent problems they had to tackle down, and on the other side there are lots of companies that have various support programs or sponsorships especially tailored for user groups. At the moment, I already have a couple of gimmicks that I would like to hand out in small contests or raffles during one of the upcoming meetings, and as said, companies provide all kind of goodies, books free of charge, or sometimes even licenses for communities. Meeting other software developers or IT guys also opens up your point of view on the local market and there might be interesting projects or job offers available, too. A community like the Mauritius Software Craftsmanship Community is great for freelancers, self-employed, students and of course employees. Meetings will be organised on a regular basis, and I'm open to all kind of suggestions from you. Please leave a comment here in blog or join the conversations in the above mentioned social networks. Let's get this community up and running, my fellow Mauritians!

    Read the article

  • When is a SQL function not a function?

    - by Rob Farley
    Should SQL Server even have functions? (Oh yeah – this is a T-SQL Tuesday post, hosted this month by Brad Schulz) Functions serve an important part of programming, in almost any language. A function is a piece of code that is designed to return something, as opposed to a piece of code which isn’t designed to return anything (which is known as a procedure). SQL Server is no different. You can call stored procedures, even from within other stored procedures, and you can call functions and use these in other queries. Stored procedures might query something, and therefore ‘return data’, but a function in SQL is considered to have the type of the thing returned, and can be used accordingly in queries. Consider the internal GETDATE() function. SELECT GETDATE(), SomeDatetimeColumn FROM dbo.SomeTable; There’s no logical difference between the field that is being returned by the function and the field that’s being returned by the table column. Both are the datetime field – if you didn’t have inside knowledge, you wouldn’t necessarily be able to tell which was which. And so as developers, we find ourselves wanting to create functions that return all kinds of things – functions which look up values based on codes, functions which do string manipulation, and so on. But it’s rubbish. Ok, it’s not all rubbish, but it mostly is. And this isn’t even considering the SARGability impact. It’s far more significant than that. (When I say the SARGability aspect, I mean “because you’re unlikely to have an index on the result of some function that’s applied to a column, so try to invert the function and query the column in an unchanged manner”) I’m going to consider the three main types of user-defined functions in SQL Server: Scalar Inline Table-Valued Multi-statement Table-Valued I could also look at user-defined CLR functions, including aggregate functions, but not today. I figure that most people don’t tend to get around to doing CLR functions, and I’m going to focus on the T-SQL-based user-defined functions. Most people split these types of function up into two types. So do I. Except that most people pick them based on ‘scalar or table-valued’. I’d rather go with ‘inline or not’. If it’s not inline, it’s rubbish. It really is. Let’s start by considering the two kinds of table-valued function, and compare them. These functions are going to return the sales for a particular salesperson in a particular year, from the AdventureWorks database. CREATE FUNCTION dbo.FetchSales_inline(@salespersonid int, @orderyear int) RETURNS TABLE AS  RETURN (     SELECT e.LoginID as EmployeeLogin, o.OrderDate, o.SalesOrderID     FROM Sales.SalesOrderHeader AS o     LEFT JOIN HumanResources.Employee AS e     ON e.EmployeeID = o.SalesPersonID     WHERE o.SalesPersonID = @salespersonid     AND o.OrderDate >= DATEADD(year,@orderyear-2000,'20000101')     AND o.OrderDate < DATEADD(year,@orderyear-2000+1,'20000101') ) ; GO CREATE FUNCTION dbo.FetchSales_multi(@salespersonid int, @orderyear int) RETURNS @results TABLE (     EmployeeLogin nvarchar(512),     OrderDate datetime,     SalesOrderID int     ) AS BEGIN     INSERT @results (EmployeeLogin, OrderDate, SalesOrderID)     SELECT e.LoginID, o.OrderDate, o.SalesOrderID     FROM Sales.SalesOrderHeader AS o     LEFT JOIN HumanResources.Employee AS e     ON e.EmployeeID = o.SalesPersonID     WHERE o.SalesPersonID = @salespersonid     AND o.OrderDate >= DATEADD(year,@orderyear-2000,'20000101')     AND o.OrderDate < DATEADD(year,@orderyear-2000+1,'20000101')     ;     RETURN END ; GO You’ll notice that I’m being nice and responsible with the use of the DATEADD function, so that I have SARGability on the OrderDate filter. Regular readers will be hoping I’ll show what’s going on in the execution plans here. Here I’ve run two SELECT * queries with the “Show Actual Execution Plan” option turned on. Notice that the ‘Query cost’ of the multi-statement version is just 2% of the ‘Batch cost’. But also notice there’s trickery going on. And it’s nothing to do with that extra index that I have on the OrderDate column. Trickery. Look at it – clearly, the first plan is showing us what’s going on inside the function, but the second one isn’t. The second one is blindly running the function, and then scanning the results. There’s a Sequence operator which is calling the TVF operator, and then calling a Table Scan to get the results of that function for the SELECT operator. But surely it still has to do all the work that the first one is doing... To see what’s actually going on, let’s look at the Estimated plan. Now, we see the same plans (almost) that we saw in the Actuals, but we have an extra one – the one that was used for the TVF. Here’s where we see the inner workings of it. You’ll probably recognise the right-hand side of the TVF’s plan as looking very similar to the first plan – but it’s now being called by a stack of other operators, including an INSERT statement to be able to populate the table variable that the multi-statement TVF requires. And the cost of the TVF is 57% of the batch! But it gets worse. Let’s consider what happens if we don’t need all the columns. We’ll leave out the EmployeeLogin column. Here, we see that the inline function call has been simplified down. It doesn’t need the Employee table. The join is redundant and has been eliminated from the plan, making it even cheaper. But the multi-statement plan runs the whole thing as before, only removing the extra column when the Table Scan is performed. A multi-statement function is a lot more powerful than an inline one. An inline function can only be the result of a single sub-query. It’s essentially the same as a parameterised view, because views demonstrate this same behaviour of extracting the definition of the view and using it in the outer query. A multi-statement function is clearly more powerful because it can contain far more complex logic. But a multi-statement function isn’t really a function at all. It’s a stored procedure. It’s wrapped up like a function, but behaves like a stored procedure. It would be completely unreasonable to expect that a stored procedure could be simplified down to recognise that not all the columns might be needed, but yet this is part of the pain associated with this procedural function situation. The biggest clue that a multi-statement function is more like a stored procedure than a function is the “BEGIN” and “END” statements that surround the code. If you try to create a multi-statement function without these statements, you’ll get an error – they are very much required. When I used to present on this kind of thing, I even used to call it “The Dangers of BEGIN and END”, and yes, I’ve written about this type of thing before in a similarly-named post over at my old blog. Now how about scalar functions... Suppose we wanted a scalar function to return the count of these. CREATE FUNCTION dbo.FetchSales_scalar(@salespersonid int, @orderyear int) RETURNS int AS BEGIN     RETURN (         SELECT COUNT(*)         FROM Sales.SalesOrderHeader AS o         LEFT JOIN HumanResources.Employee AS e         ON e.EmployeeID = o.SalesPersonID         WHERE o.SalesPersonID = @salespersonid         AND o.OrderDate >= DATEADD(year,@orderyear-2000,'20000101')         AND o.OrderDate < DATEADD(year,@orderyear-2000+1,'20000101')     ); END ; GO Notice the evil words? They’re required. Try to remove them, you just get an error. That’s right – any scalar function is procedural, despite the fact that you wrap up a sub-query inside that RETURN statement. It’s as ugly as anything. Hopefully this will change in future versions. Let’s have a look at how this is reflected in an execution plan. Here’s a query, its Actual plan, and its Estimated plan: SELECT e.LoginID, y.year, dbo.FetchSales_scalar(p.SalesPersonID, y.year) AS NumSales FROM (VALUES (2001),(2002),(2003),(2004)) AS y (year) CROSS JOIN Sales.SalesPerson AS p LEFT JOIN HumanResources.Employee AS e ON e.EmployeeID = p.SalesPersonID; We see here that the cost of the scalar function is about twice that of the outer query. Nicely, the query optimizer has worked out that it doesn’t need the Employee table, but that’s a bit of a red herring here. There’s actually something way more significant going on. If I look at the properties of that UDF operator, it tells me that the Estimated Subtree Cost is 0.337999. If I just run the query SELECT dbo.FetchSales_scalar(281,2003); we see that the UDF cost is still unchanged. You see, this 0.0337999 is the cost of running the scalar function ONCE. But when we ran that query with the CROSS JOIN in it, we returned quite a few rows. 68 in fact. Could’ve been a lot more, if we’d had more salespeople or more years. And so we come to the biggest problem. This procedure (I don’t want to call it a function) is getting called 68 times – each one between twice as expensive as the outer query. And because it’s calling it in a separate context, there is even more overhead that I haven’t considered here. The cheek of it, to say that the Compute Scalar operator here costs 0%! I know a number of IT projects that could’ve used that kind of costing method, but that’s another story that I’m not going to go into here. Let’s look at a better way. Suppose our scalar function had been implemented as an inline one. Then it could have been expanded out like a sub-query. It could’ve run something like this: SELECT e.LoginID, y.year, (SELECT COUNT(*)     FROM Sales.SalesOrderHeader AS o     LEFT JOIN HumanResources.Employee AS e     ON e.EmployeeID = o.SalesPersonID     WHERE o.SalesPersonID = p.SalesPersonID     AND o.OrderDate >= DATEADD(year,y.year-2000,'20000101')     AND o.OrderDate < DATEADD(year,y.year-2000+1,'20000101')     ) AS NumSales FROM (VALUES (2001),(2002),(2003),(2004)) AS y (year) CROSS JOIN Sales.SalesPerson AS p LEFT JOIN HumanResources.Employee AS e ON e.EmployeeID = p.SalesPersonID; Don’t worry too much about the Scan of the SalesOrderHeader underneath a Nested Loop. If you remember from plenty of other posts on the matter, execution plans don’t push the data through. That Scan only runs once. The Index Spool sucks the data out of it and populates a structure that is used to feed the Stream Aggregate. The Index Spool operator gets called 68 times, but the Scan only once (the Number of Executions property demonstrates this). Here, the Query Optimizer has a full picture of what’s being asked, and can make the appropriate decision about how it accesses the data. It can simplify it down properly. To get this kind of behaviour from a function, we need it to be inline. But without inline scalar functions, we need to make our function be table-valued. Luckily, that’s ok. CREATE FUNCTION dbo.FetchSales_inline2(@salespersonid int, @orderyear int) RETURNS table AS RETURN (SELECT COUNT(*) as NumSales     FROM Sales.SalesOrderHeader AS o     LEFT JOIN HumanResources.Employee AS e     ON e.EmployeeID = o.SalesPersonID     WHERE o.SalesPersonID = @salespersonid     AND o.OrderDate >= DATEADD(year,@orderyear-2000,'20000101')     AND o.OrderDate < DATEADD(year,@orderyear-2000+1,'20000101') ); GO But we can’t use this as a scalar. Instead, we need to use it with the APPLY operator. SELECT e.LoginID, y.year, n.NumSales FROM (VALUES (2001),(2002),(2003),(2004)) AS y (year) CROSS JOIN Sales.SalesPerson AS p LEFT JOIN HumanResources.Employee AS e ON e.EmployeeID = p.SalesPersonID OUTER APPLY dbo.FetchSales_inline2(p.SalesPersonID, y.year) AS n; And now, we get the plan that we want for this query. All we’ve done is tell the function that it’s returning a table instead of a single value, and removed the BEGIN and END statements. We’ve had to name the column being returned, but what we’ve gained is an actual inline simplifiable function. And if we wanted it to return multiple columns, it could do that too. I really consider this function to be superior to the scalar function in every way. It does need to be handled differently in the outer query, but in many ways it’s a more elegant method there too. The function calls can be put amongst the FROM clause, where they can then be used in the WHERE or GROUP BY clauses without fear of calling the function multiple times (another horrible side effect of functions). So please. If you see BEGIN and END in a function, remember it’s not really a function, it’s a procedure. And then fix it. @rob_farley

    Read the article

< Previous Page | 36 37 38 39 40 41 42 43 44 45 46 47  | Next Page >