Search Results

Search found 137428 results on 5498 pages for 'using statement'.

Page 9/5498 | < Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >

  • SQL SERVER – Solution of Puzzle – Swap Value of Column Without Case Statement

    - by pinaldave
    Earlier this week I asked a question where I asked how to Swap Values of the column without using CASE Statement. Read here: SQL SERVER – A Puzzle – Swap Value of Column Without Case Statement. I have proposed 3 different solutions in the blog posts itself. I had requested the help of the community to come up with alternate solutions and honestly I am stunned and amazed by the qualified entries. I will be not able to cover every single solution which is posted as a comment, however, I would like to for sure cover few interesting entries. However, I am selecting 5 solutions which are different (not necessary they are most optimal or best – just different and interesting). Just for clarity I am involving the original problem statement here. USE tempdb GO CREATE TABLE SimpleTable (ID INT, Gender VARCHAR(10)) GO INSERT INTO SimpleTable (ID, Gender) SELECT 1, 'female' UNION ALL SELECT 2, 'male' UNION ALL SELECT 3, 'male' GO SELECT * FROM SimpleTable GO -- Insert Your Solutions here -- Swap value of Column Gender SELECT * FROM SimpleTable GO DROP TABLE SimpleTable GO Here are the five most interesting and different solutions I have received. Solution by Roji P Thomas UPDATE S SET S.Gender = D.Gender FROM SimpleTable S INNER JOIN SimpleTable D ON S.Gender != D.Gender I really loved the solutions as it is very simple and drives the point home – elegant and will work pretty much for any values (not necessarily restricted by the option in original question ‘male’ or ‘female’). Solution by Aneel CREATE TABLE #temp(id INT, datacolumn CHAR(4)) INSERT INTO #temp VALUES(1,'gent'),(2,'lady'),(3,'lady') DECLARE @value1 CHAR(4), @value2 CHAR(4) SET @value1 = 'lady' SET @value2 = 'gent' UPDATE #temp SET datacolumn = REPLACE(@value1 + @value2,datacolumn,'') Aneel has very interesting solution where he combined both the values and replace the original value. I personally liked this creativity of the solution. Solution by SIJIN KUMAR V P UPDATE SimpleTable SET Gender = RIGHT(('fe'+Gender), DIFFERENCE((Gender),SOUNDEX(Gender))*2) Sijin has amazed me with Difference and Soundex function. I have never visualized that above two functions can resolve the problem. Hats off to you Sijin. Solution by Nikhildas UPDATE St SET St.Gender = t.Gender FROM SimpleTable St CROSS Apply (SELECT DISTINCT gender FROM SimpleTable WHERE St.Gender != Gender) t I was expecting that someone will come up with this solution where they use CROSS APPLY. This is indeed very neat and for sure interesting exercise. If you do not know how CROSS APPLY works this is the time to learn. Solution by mistermagooo UPDATE SimpleTable SET Gender=X.NewGender FROM (VALUES('male','female'),('female','male')) AS X(OldGender,NewGender) WHERE SimpleTable.Gender=X.OldGender As per author this is a slow solution but I love how syntaxes are placed and used here. I love how he used syntax here. I will say this is the most beautifully written solution (not necessarily it is best). Bonus: Solution by Madhivanan Somehow I was confident Madhi – SQL Server MVP will come up with something which I will be compelled to read. He has written a complete blog post on this subject and I encourage all of you to go ahead and read it. Now personally I wanted to list every single comment here. There are some so good that I am just amazed with the creativity. I will write a part of this blog post in future. However, here is the challenge for you. Challenge: Go over 50+ various solutions listed to the simple problem here. Here are my two asks for you. 1) Pick your best solution and list here in the comment. This exercise will for sure teach us one or two things. 2) Write your own solution which is yet not covered already listed 50 solutions. I am confident that there is no end to creativity. Reference: Pinal Dave (http://blog.SQLAuthority.com) Filed under: PostADay, SQL, SQL Authority, SQL Function, SQL Puzzle, SQL Query, SQL Server, SQL Tips and Tricks, T SQL, Technology

    Read the article

  • Dynamically Insert Variables into DB Table using PreparedStatement

    - by gran_profaci
    I was working with PreparedStatement today and noticed that it used setString() setTimestamp() etc. to insert variables into the DB. I basically have 20 tables each with at least 15 columns and it would not be feasible for me to manuallt write down all the setters. Considering that I have an ArrayList "Vals" which contains all the variables to be inputted in String format (obtained by getString() using PreparedStatement itself), is there any way I can do an insert without using expressly using the Setters? That would save me a lot of time.

    Read the article

  • Detect if any USB drive is detected or if not using WinForm Application in Visual C#

    - by Pavan Kumar
    I want to do the following things in my application 1) I want to display whether any USB drive is inserted or not in my application to prompt the user to insert a USB drive. I just want to notify the user if any USB dirve is inserted else prompt him to insert one using a label or something (i want to avoid messagebox as it will keep appearing whenever a device is inserted or removed. It will be irritating for the end user) in my Visual C# WinForm Application. If any USB drive is present display "USB drive detected" in the label. The user may add one or more USB sticks but the status will remain same. When there is none then the status of the label will change to "No USB drives found.Please insert a USB drive". 2) When one or more USB drive is added the volume name with the drive letter for example "James(F:)" is added to the Combobox list. The combobox list also needs to remove the entry for the USB drive added in the list automatically when it is removed . So when there is no USB the list should be empty and the label will again prompt user to insert a USB stick or drive.

    Read the article

  • Detect if any USB drive is detected or not using WinForm Application in Visual C#

    - by Pavan Kumar
    I want to do the following things in my application 1) I want to display whether any USB drive is inserted or not in my application to prompt the user to insert a USB drive. I just want to notify the user if any USB dirve is inserted else prompt him to insert one using a label or something (i want to avoid messagebox as it will keep appearing whenever a device is inserted or removed. It will be irritating for the end user) in my Visual C# WinForm Application. If any USB drive is present display "USB drive detected" in the label. The user may add one or more USB sticks but the status will remain same. When there is none then the status of the label will change to "No USB drives found.Please insert a USB drive". 2) When one or more USB drive is added the volume name with the drive letter for example "James(F:)" is added to the Combobox list. The combobox list also needs to remove the entry for the USB drive added in the list automatically when it is removed . So when there is no USB the list should be empty and the label will again prompt user to insert a USB stick or drive.

    Read the article

  • C# - using decimal in switch impossible?

    - by phobia
    Hi, I'm justing starting out learning C# and I've become stuck at something very basic. For my first "app" I thought I'd go for something simple, so I decided for a BMI calculator. The BMI is calculated into a decimal type which I'm now trying to use in a switch statement, but aparently decimal can't be used in a switch? What would be the C# solution for this: decimal bmi = calculate_bmi(h, w); switch (bmi) { case < 18.5: bmi_description = "underweight."; break; case > 25: bmi_description = "overweight"; case > 30: bmi_description = "very overweight"; case > 40: bmi_description = "extreme overweight"; break; } Thanks in advance :)

    Read the article

  • Making a switch statement in C with an array?

    - by Eric
    I am trying to make a switch statement that takes in a word into an array and then throws each letter through a switch statement and allocates a point to each letter depending on which letter it is and giving a final point value for the word, and I can't seem to get the array part right. Any help would be appreciated! int main(){ int letter_points = 0; char word[7]; int word_length = 7; int i; printf("Enter a Word\n"); scanf("%s", word); for(i = 0; i < word_length; i++){ switch(word){ //1 point case 'A': case 'E': case 'I': case 'L': case 'N': case 'O': case 'R': case 'S': case 'T': case 'U': letter_points++; break; //2 points case 'D': case 'G': letter_points += 2; break; //3 points case 'B': case 'C': case 'M': case 'P': letter_points += 3; break; //4 points case 'F': case 'H': case 'V': case 'W': case 'Y': letter_points += 4; break; //5 points case 'K': letter_points += 5; break; //8 points case 'J': case 'X': letter_points += 8; break; //10 points case 'Q': case 'Z': letter_points += 10; break; } } printf("%d\n", letter_points); return; }

    Read the article

  • What characters are NOT escaped with a mysqli prepared statement?

    - by barfoon
    Hey everyone, I'm trying to harden some of my PHP code and use mysqli prepared statements to better validate user input and prevent injection attacks. I switched away from mysqli_real_escape_string as it does not escape % and _. However, when I create my query as a mysqli prepared statement, the same flaw is still present. The query pulls a users salt value based on their username. I'd do something similar for passwords and other lookups. Code: $db = new sitedatalayer(); if ($stmt = $db->_conn->prepare("SELECT `salt` FROM admins WHERE `username` LIKE ? LIMIT 1")) { $stmt->bind_param('s', $username); $stmt->execute(); $stmt->bind_result($salt); while ($stmt->fetch()) { printf("%s\n", $salt); } $stmt->close(); } else return false; Am I composing the statement correctly? If I am what other characters need to be examined? What other flaws are there? What is best practice for doing these types of selects? Thanks,

    Read the article

  • Error when upgrading initscripts using dist-upgrade on a cd image using uck

    - by InkBlend
    I was using UCK to customize an Ubuntu 11.10 image, and ran a dist-upgrade on it (from the console) to try to update all of the packages on it. The upgrade worked successfully for all but two packages, so I tried again and got the same error message. This is what happened: # sudo apt-get dist-upgrade Reading package lists... Done Building dependency tree Reading state information... Done Calculating upgrade... Done 0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded. 2 not fully installed or removed. After this operation, 0 B of additional disk space will be used. Do you want to continue [Y/n]? y Setting up initscripts (2.88dsf-13.10ubuntu4.1) ... guest environment detected: Linking /run/shm to /dev/shm rmdir: failed to remove `/run/shm': Device or resource busy Can't symlink /run/shm to /dev/shm; please fix manually. dpkg: error processing initscripts (--configure): subprocess installed post-installation script returned error exit status 1 No apport report written because MaxReports is reached already dpkg: dependency problems prevent configuration of ifupdown: ifupdown depends on initscripts (>= 2.88dsf-13.3); however: Package initscripts is not configured yet. dpkg: error processing ifupdown (--configure): dependency problems - leaving unconfigured No apport report written because MaxReports is reached already Errors were encountered while processing: initscripts ifupdown E: Sub-process /usr/bin/dpkg returned an error code (1) # How can I fix this? Is the problem with the ISO, dpkg, or can I just not upgrade some packages with UCK? I am using Ubuntu 11.10 to and UCK 2.4.5 to customize an Ubuntu 11.10 image.

    Read the article

  • Implementing a switch statement based on user input

    - by Dave Voyles
    I'm trying to delay the time it takes for the main menu screen to pop up after a user has won / lost a match. As it stands, the game immediately displays a message stating "you won / lost" and waits for 6 seconds before loading the menu screen. I would also like players to have the ability to press a key to advance to the menu screen immediately but thus far my switch statement doesn't seem to do the trick. I've included the switch statement, along with my (theoretical) inputs. What could I be doing wrong here? if (gamestate == GameStates.End) switch (input.IsMenuDown(ControllingPlayer)) { case true: ScreenManager.AddScreen(new MainMenuScreen(), null); // Draws the MainMenuScreen break; case false: if (screenLoadDelay > 0) { screenLoadDelay -= gameTime.ElapsedGameTime.TotalSeconds; } ScreenManager.AddScreen(new MainMenuScreen(), null); // Draws the MainMenuScreen break; } /// <summary> /// Checks for a "menu down" input action. /// The controllingPlayer parameter specifies which player to read /// input for. If this is null, it will accept input from any player. /// </summary> public bool IsMenuDown(PlayerIndex? controllingPlayer) { PlayerIndex playerIndex; return IsNewKeyPress(Keys.Down, controllingPlayer, out playerIndex) || IsNewButtonPress(Buttons.DPadDown, controllingPlayer, out playerIndex) || IsNewButtonPress(Buttons.LeftThumbstickDown, controllingPlayer, out playerIndex); }

    Read the article

  • JDBC delete statement with multiple columns

    - by user1643033
    It says I ended this statement wrong when if I input it into sql plus with just the addition of ; it works perfectly. What am I doing wrong? Statement statement = connection.createStatement(); statement.executeUpdate("delete from aplbuk MODEL = '"+ textField_4.getText() + "'AND year = '" + textField_1.getText() + "' AND Litres = '" + textField_2.getText() + "' AND ENGINE_TYPE = '" + textField_3.getText() + "'"); statement.close();

    Read the article

  • Publishing SWF using Adobe Flash

    - by Kim
    Hello everyone, I have a SWF file which contains of an image (1keyframe) and also, it contains an AS3 file with the following codes: var loader:Loader=new Loader(); var ur:URLRequest=new URLRequest("1.swf"); loader.load(ur); addChild(loader); so basically, i am trying to play the swf file (1.swf - an audio) while the image is being displayed. What I want to know is how will I be able to publish this project into an SWF file which can still play as expected even without the raw 1.swf file. I can publish SWF right now but when I delete the 1.swf file, my generated swf can only display the image. Help me please. Thanks in advance :)

    Read the article

  • how to get records from subquery using union in linq

    - by varun
    sql = " SELECT * FROM userDetail "; sql += " WHERE userId IN "; sql += " (SELECT friendId FROM userFriends "; sql += " WHERE approvalStatus='True' AND userId=" + userId; sql += " UNION"; sql += " SELECT userId FROM userFriends "; sql += " WHERE approvalStatus='True' AND friendId=" + userId + ")";

    Read the article

  • Interfaces with structs, by reference using Generics

    - by Fraga
    I can't pass by reference an interface with a struct in it, what am I doing wrong? Here is the example code: class Processor<T> where T : new() { public Processor() { Data = new T(); } public T Data; } class PeriodsProcessor : Processor<Periods> { public PeriodsProcessor() { DataBase DB = new DataBase(); Console.WriteLine(Data.Value); DB.ModifyData<Period>(Data); Console.WriteLine(Data.Value); Console.ReadLine(); } } public class Period { public string Name; } public interface IDataTable<T> { string Value { get; set; } T Filter { get; set; } } [Serializable] public struct Periods : IDataTable<Period> { public string Value { get; set; } public Period Filter { get; set; } } public class DataBase { public void ModifyData<T>(IDataTable<T> data) where T : new() { data.Value = "CHANGE"; } } class Program { static void Main(string[] args) { PeriodsProcessor PeriodsProcessor = new PeriodsProcessor(); } }

    Read the article

  • Provisioning Api using java

    - by user268515
    Hi i'm working in java and tried to retrieve all the user in the domain for that i used Provisionin api............ Its working good But my idea is to Use 2-legged OAuth to retrieve the users from the domain Is it Possible? I dont how to specify the URL please Help me And i triede the following the program final String CONSUMER_KEY = "xxxxxxxxxx.com"; final String CONSUMER_SECRET = "12345678122154154df9"; final String DOMAIN = "xxxxxxxxxx.com"; GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters(); oauthParameters.setOAuthConsumerKey(CONSUMER_KEY); oauthParameters.setOAuthConsumerSecret(CONSUMER_SECRET); oauthParameters.setOAuthType(OAuthType.TWO_LEGGED_OAUTH); OAuthHmacSha1Signer signer = new OAuthHmacSha1Signer(); URL feedUrl = new URL("https://apps-apis.google.com/a/feeds/" + DOMAIN + "/user/2.0/[email protected]"); userService = new UserService("Myapplication"); userService.setOAuthCredentials(oauthParameters, signer); userService.useSsl(); UserFeed allUsers = new UserFeed(); UserFeed allpage; Link nextLink; do { allpage = userService.getFeed(feedUrl, UserFeed.class); allUsers.getEntries().addAll(allpage.getEntries()); nextLink = allpage.getLink(Link.Rel.NEXT, Link.Type.ATOM); if (nextLink != null) { feedUrl = new URL(nextLink.getHref()); } }while (nextLink != null); return allUsers; } Its returing the error as com.google.gdata.util.AuthenticationException: Unknown authorization header

    Read the article

  • Using Ops Center to Provision Solaris using a Card-Based NIC

    - by Larry Wake
    Scott Dickson writes:  "Here's what I want to do:  I have a Sun Fire T2000 server with a Quad-GbE nxge card installed.  The only network is connected to port 2 on that card rather than the built-in network interfaces.  I want to install Solaris on it across the network, either Solaris 10 or Solaris 11." See what he did, using Oracle Enterprise Manager Ops Center 12c. [Read More]

    Read the article

  • Using prepared statements with JDBCTemplate

    - by Bernhard V
    Hi. I'm using the Jdbc template and want to read from the database using prepared statements. I iterate over many lines in a csv file and on every line I execute some sql select queries with it's values. Now I want to speed up my reading from the database but I just can't get the Jdbc template to work with prepared statements. Actually I even don't know how to do it. There is the PreparedStatementCreator and the PreparedStatementCreator. As in this example both of them are created with anonymous inner classes. But inside the PreparedStatementCreator class I don't have access to the values I want to set in the prepared statement. Since I'm iterating through a csv file I can't hard code them as a String because I don't know them. I also can't pass them to the PreparedStatementCreator because there are no arguments for the constructor. I was used to the creation of prepared statements being fairly simple. Something like PreparedStatement updateSales = con.prepareStatement( "UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ? "); updateSales.setInt(1, 75); updateSales.setString(2, "Colombian"); updateSales.executeUpdate(): as in the Java tutorial. Your help would be very appreciated.

    Read the article

  • Using PHP to display button with hyperlink or greyed out button if no URL in database

    - by Diane
    I've got a webpage that I'm working on where you click on a letter or category and it displays records matching that query from a database. One of the things I want to display is a hyperlinked button that says "Website" if the database record contains a URL in the 'URL' field, and if there is no value in that field, it will display a greyed out version of that button. I tried using an if...else statement, but was absolutely unable to get the syntax correct trying to get php to call up the 'URL' value in the middle of an "echo " So here's what I did: <?php if($row_rsmemalpha['URL'] != NULL) ?><a href="http://<?php echo ($row_rsmemalpha['URL']);?>"><target ="_blank"><img src="web_button_on.gif" alt="Website" border="0" height="18" width="103" /></target></a> <?php if($row_rsmemalpha['URL'] == NULL) echo "<img src=\"web_button_off.gif\" alt=\"No Website Available\" height=\"18\" width=\"103\" />"; ?> If there is a URL available it shows the button properly. But if there isn't a URL in the database it shows both buttons. I have spent a few days studying examples and tutorials on the web, but haven't found too much that helps. The buttons were completely non-functional when I started, so I'm pretty proud of getting this far with it! I've just run out of time and patience for more trial-and-error experimenting. Any help is appreciated... Diane

    Read the article

  • Non-blocking I/O using Servlet 3.1: Scalable applications using Java EE 7 (TOTD #188)

    - by arungupta
    Servlet 3.0 allowed asynchronous request processing but only traditional I/O was permitted. This can restrict scalability of your applications. In a typical application, ServletInputStream is read in a while loop. public class TestServlet extends HttpServlet {    protected void doGet(HttpServletRequest request, HttpServletResponse response)         throws IOException, ServletException {     ServletInputStream input = request.getInputStream();       byte[] b = new byte[1024];       int len = -1;       while ((len = input.read(b)) != -1) {          . . .        }   }} If the incoming data is blocking or streamed slower than the server can read then the server thread is waiting for that data. The same can happen if the data is written to ServletOutputStream. This is resolved in Servet 3.1 (JSR 340, to be released as part Java EE 7) by adding event listeners - ReadListener and WriteListener interfaces. These are then registered using ServletInputStream.setReadListener and ServletOutputStream.setWriteListener. The listeners have callback methods that are invoked when the content is available to be read or can be written without blocking. The updated doGet in our case will look like: AsyncContext context = request.startAsync();ServletInputStream input = request.getInputStream();input.setReadListener(new MyReadListener(input, context)); Invoking setXXXListener methods indicate that non-blocking I/O is used instead of the traditional I/O. At most one ReadListener can be registered on ServletIntputStream and similarly at most one WriteListener can be registered on ServletOutputStream. ServletInputStream.isReady and ServletInputStream.isFinished are new methods to check the status of non-blocking I/O read. ServletOutputStream.canWrite is a new method to check if data can be written without blocking.  MyReadListener implementation looks like: @Overridepublic void onDataAvailable() { try { StringBuilder sb = new StringBuilder(); int len = -1; byte b[] = new byte[1024]; while (input.isReady() && (len = input.read(b)) != -1) { String data = new String(b, 0, len); System.out.println("--> " + data); } } catch (IOException ex) { Logger.getLogger(MyReadListener.class.getName()).log(Level.SEVERE, null, ex); }}@Overridepublic void onAllDataRead() { System.out.println("onAllDataRead"); context.complete();}@Overridepublic void onError(Throwable t) { t.printStackTrace(); context.complete();} This implementation has three callbacks: onDataAvailable callback method is called whenever data can be read without blocking onAllDataRead callback method is invoked data for the current request is completely read. onError callback is invoked if there is an error processing the request. Notice, context.complete() is called in onAllDataRead and onError to signal the completion of data read. For now, the first chunk of available data need to be read in the doGet or service method of the Servlet. Rest of the data can be read in a non-blocking way using ReadListener after that. This is going to get cleaned up where all data read can happen in ReadListener only. The sample explained above can be downloaded from here and works with GlassFish 4.0 build 64 and onwards. The slides and a complete re-run of What's new in Servlet 3.1: An Overview session at JavaOne is available here. Here are some more references for you: Java EE 7 Specification Status Servlet Specification Project JSR Expert Group Discussion Archive Servlet 3.1 Javadocs

    Read the article

  • Using array instead of lots of db queries in PHP

    - by Tural Teyyuboglu
    My function looks like that. It works but does lots of work (recursively calls itself and does lots of db queries.). There must be another way to do same thing but with array (with one query). I can't figure out how to modify this function to get it work with array. Please help. function genMenu($parent, $level, $menu, $utype) { global $db; $stmt=$db->prepare("select id, name FROM navigation WHERE parent = ? AND menu=? AND user_type=?") or die($db->error); $stmt->bind_param("iii", $parent, $menu, $utype) or die($stmt->error); $stmt->execute() or die($stmt->error); $stmt->store_result(); /* bind variables to prepared statement */ $stmt->bind_result($id, $name) or die($stmt->error); if ($level > 0 && $stmt->num_rows > 0) { echo "\n<ul>\n"; } while ($stmt->fetch()) { echo "<li>"; echo '<a href="?page=' . $id . '">' . $name . '</a>'; //display this level's children genMenu($id, $level+1, $menu, $utype); echo "</li>\n\n"; } if ($level > 0 && $stmt->num_rows > 0) { echo "</ul>\n"; } $stmt->close(); }

    Read the article

  • How do I write a prepared statement with an update?

    - by Chris
    I am using mysqli prepared statments and I am trying to write a prepared statement with an UPDATE, but I think I am off somewhere. Here's my code: $upload_folder = 'Some String'; $sql = 'UPDATE orders (upload_location) SET (?) WHERE order_id = 160'; $stmt = $conn->stmt_init(); if($stmt->prepare($sql)){ $stmt->bind_param('s', $upload_folder); $location_inserted = $stmt->execute(); } What am I doing wrong?

    Read the article

< Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >