Search Results

Search found 5122 results on 205 pages for 'max arderius'.

Page 24/205 | < Previous Page | 20 21 22 23 24 25 26 27 28 29 30 31  | Next Page >

  • Random generates same number in java

    - by user1613360
    This is my java code. import java.io.*; import java.util.*; import java.util.concurrent.TimeUnit; class search { private int numelem; private int[] input=new int[100]; public void setNumofelem() { System.out.println("Enter the total numebr of elements"); Scanner yz=new Scanner(System.in); numelem=yz.nextInt(); } public void randomnumber() throws Exception { int max=500,min=1,n=numelem; Random rand = new Random(); for (int j=0;j < n;j++) { input[j]=rand.nextInt(max)+1; } } public void printinput() { int b=numelem,t=0; while(true) if(b!=0) { System.out.print(" "+input[t]); b--; t++; } else break; } } public class mycode { public static void main(String args[]) throws Exception { search a=new search(); a.setNumofelem(); a.randomnumber(); a.printinput(); } } Now the function randomnumber() just returns the same number.The function executes perfectly if I execute it as a separate java program but fails miserably if I call it using an object.I have also tried the following variations but nothing works everything return the same number. Variation 1: public void randomnumber() throws Exception { int max=500,min=1,n=numelem; Random rand = new Random(); for (int j=0;j < n;j++) { TimeUnit.SECONDS.sleep(1); input[j]=rand.nextInt(max)+1; } } Variation 2: public void randomnumber() throws Exception { int max=500,min=1,n=numelem; Random rand = new Random(); for (int j=0;j < n;j++) { rand.setSeed(System.nanoTime()); input[j]=rand.nextInt(max)+1; } } Variation 3: public void randomnumber() throws Exception { int max=500,min=1,n=numelem; Random rand = new Random(); for (int j=0;j < n;j++) { TimeUnit.SECONDS.sleep(1); rand.setSeed(System.nanoTime()); input[j]=rand.nextInt(max)+1; } } Sample input/Output: Enter the number of elements: 5 23 23 23 23 23 23

    Read the article

  • Getting maximum value of float in SQL programatically

    - by Axarydax
    Is there an method for programatically (in T-SQL) retrieving the maximum (and minimum) value of a datatype? That it would act like float.MaxValue in C#. I would like to use it in some selection when the parameter does not equal any actual values in the database, so I would use something like declare @min float declare @max float /*fill @min and @max, can be null if undefined*/ select * from foo where bar between isnull(@min,0 ), isnull(@max,max(float)/*magic*/) Thanks

    Read the article

  • C++ boost function overloaded template

    - by aaa
    I cannot figure out why this segment gives unresolved overloaded function error (gcc version 4.3.4 (Debian 4.3.4-6)): #include <algorithm> #include <boost/function.hpp> int main { typedef boost::function2<const int&, const int&, const int&> max; max m(static_cast<max>(&std::max<int>)); } can you help me, thanks

    Read the article

  • Why does limiting my virtual memory to 512MB with ulimit -v crash the JVM?

    - by Narinder Kumar
    I am trying to enforce maximum memory a program can consume on a Unix system. I thought ulimit -v should do the trick. Here is a sample Java program I have written for testing : import java.util.*; import java.io.*; public class EatMem { public static void main(String[] args) throws IOException, InterruptedException { System.out.println("Starting up..."); System.out.println("Allocating 128 MB of Memory"); List<byte[]> list = new LinkedList<byte[]>(); list.add(new byte[134217728]); //128 MB System.out.println("Done...."); } } By default, my ulimit settings are (output of ulimit -a) : core file size (blocks, -c) 0 data seg size (kbytes, -d) unlimited scheduling priority (-e) 0 file size (blocks, -f) unlimited pending signals (-i) 31398 max locked memory (kbytes, -l) 64 max memory size (kbytes, -m) unlimited open files (-n) 1024 pipe size (512 bytes, -p) 8 POSIX message queues (bytes, -q) 819200 real-time priority (-r) 0 stack size (kbytes, -s) 8192 cpu time (seconds, -t) unlimited max user processes (-u) 31398 virtual memory (kbytes, -v) unlimited file locks (-x) unlimited When I execute my java program (java EatMem), it executes without any problems. Now I try to limit max memory available to any program launched in the current shell to 512MB by launching the following command : ulimit -v 524288 ulimit -a output shows the limit to be set correctly (I suppose): core file size (blocks, -c) 0 data seg size (kbytes, -d) unlimited scheduling priority (-e) 0 file size (blocks, -f) unlimited pending signals (-i) 31398 max locked memory (kbytes, -l) 64 max memory size (kbytes, -m) unlimited open files (-n) 1024 pipe size (512 bytes, -p) 8 POSIX message queues (bytes, -q) 819200 real-time priority (-r) 0 stack size (kbytes, -s) 8192 cpu time (seconds, -t) unlimited max user processes (-u) 31398 virtual memory (kbytes, -v) 524288 file locks (-x) unlimited If I now try to execute my java program, it gives me the following error: Error occurred during initialization of VM Could not reserve enough space for object heap Could not create the Java virtual machine. Ideally it should not happen as my Java program is only taking around 128MB of memory which is well within my specified ulimit parameters. If I change the arguments to my Java program as below: java -Xmx256m EatMem The program again works fine. While trying to give more memory than limited by ulimit like : java -Xmx800m EatMem results in expected error. Why the program fails to execute in the first case after setting ulimit ? I have tried the above test on Ubuntu 11.10 and 12.0.4 with Java 1.6 and Java 7

    Read the article

  • Best Processor for MediaSmart Server?

    - by Kent Boogaart
    I'm trying to figure out what the best possible processor is that I can stick in my HP MediaSmart server. I'm clueless when it comes to correlating CPUs to motherboards. I suspect it's the socket type I care about, but I worry that there's more to it. CPU-Z gives me (excerpt): Processors Information ------------------------------------------------------------------------- Processor 1 ID = 0 Number of cores 1 (max 1) Number of threads 1 (max 1) Name AMD Sempron LE-1150 Codename Sparta Specification AMD Sempron(tm) Processor LE-1150 Package Socket AM2 (940) CPUID F.F.1 Extended CPUID F.7F Brand ID 1 Core Stepping DH-G1 Technology 65 nm Core Speed 1000.0 MHz Multiplier x FSB 5.0 x 200.0 MHz HT Link speed 800.0 MHz Stock frequency 2000 MHz Instructions sets MMX (+), 3DNow! (+), SSE, SSE2, SSE3, x86-64 L1 Data cache 64 KBytes, 2-way set associative, 64-byte line size L1 Instruction cache 64 KBytes, 2-way set associative, 64-byte line size L2 cache 256 KBytes, 16-way set associative, 64-byte line size FID/VID Control yes Max FID 10.0x Max VID 1.350 V P-State FID 0x2 - VID 0x12 (5.0x - 1.100 V) P-State FID 0xA - VID 0x0C (9.0x - 1.250 V) P-State FID 0xC - VID 0x0A (10.0x - 1.300 V) K8 Thermal sensor yes K8 Revision ID 6.0 Attached device PCI device at bus 0, device 24, function 0 Attached device PCI device at bus 0, device 24, function 1 Attached device PCI device at bus 0, device 24, function 2 Attached device PCI device at bus 0, device 24, function 3 Chipset ------------------------------------------------------------------------- Northbridge SiS 761GX rev. 02 Southbridge SiS 966 rev. 59 Graphic Interface AGP AGP Revision 3.0 AGP Transfer Rate 8x AGP SBA supported, enabled Memory Type DDR2 Memory Size 2048 MBytes Channels Single Memory Frequency 200.0 MHz (CPU/5) CAS# latency (CL) 5.0 RAS# to CAS# delay (tRCD) 5 RAS# Precharge (tRP) 5 Cycle Time (tRAS) 15 Bank Cycle Time (tRC) 21 Command Rate (CR) 1T DMI ------------------------------------------------------------------------- DMI BIOS vendor Phoenix Technologies, LTD version R03 date 05/08/2008 DMI System Information manufacturer HP product MediaSmart Server version unknown serial CN68330DGH UUID A482007B-B0CC7593-DD11736A-407B7067 DMI Baseboard vendor Wistron model SJD4 revision A.0 serial unknown DMI System Enclosure manufacturer HP chassis type Desktop chassis serial unknown DMI Processor manufacturer AMD model AMD Sempron(tm) Processor LE-1150 clock speed 2000.0 MHz FSB speed 200.0 MHz multiplier 10.0x DMI Memory Controller correction 64-bit ECC Max module size 4096 MBytes DMI Memory Module designation A0 size 2048 MBytes (double bank) DMI Memory Module designation A1 DMI Memory Module designation A2 DMI Memory Module designation A3 DMI Port Connector designation PS/2 Mouse (internal) port type Mouse Port connector PS/2 connector PS/2 DMI Port Connector designation USB0 (external) port type USB DMI Physical Memory Array location Motherboard usage System Memory correction None max capacity 16384 MBytes max# of devices 4 DMI Memory Device designation A0 format DIMM type unknown total width 64 bits data width 64 bits size 2048 MBytes DMI Memory Device designation A1 format DIMM type unknown total width 64 bits data width 64 bits DMI Memory Device designation A2 format DIMM type unknown total width 64 bits data width 64 bits DMI Memory Device designation A3 format DIMM type unknown total width 64 bits data width 64 bits How do I figure out what options I have for an upgrade?

    Read the article

  • c++ programming- Tryin to get a number within an array that is twice the average

    - by max
    i have been assigned to set up an array with points. I am told to get the maximum value, average, nd within this same array, if any point in the array is twice the average, i should cout an "outlier." So far i have gotten the average and maximum numbers in the array. but i am unable to set the programme to cout the outlier. Instead it gives me a multiple of the average. pls help! here is the programme; int main() { const int max = 10; int ary[max]={4, 32, 9, 7, 14, 12, 13, 17, 19, 18}; int i,maxv; double out,sum=0; double av; maxv= ary[0]; for(i=0; i } cout<<"maximum value: "< for(i=0; i sum = sum + ary[i]; av = sum / max; } cout<<"average: "< out = av * 2; if(ary[i]out) { cout<<"outlier: "< return 0; }

    Read the article

  • korgac - init.d kill script on shutdown

    - by Max Magnus
    I'm new to Ubuntu 12.04 and Linux and my English is not the best, so I'm sorry for incorrect or stupid questions. I've installed KOrganizer and to start the reminder when I boot the system, I added the korgac command to the autostart. This works fine. But now, every time I want to reboot or shutdown my system, there appears a message that tells me that an unknown process is still running... so I have kill it manually before reboot/shutdown. I knew that it is the korgac process that causes this problem, so I decided to create an init.d script. I've created a script, put it into init.d, and created 2 symbolic links: to rc0.d and to rc6.d. The name starts with K10script... (I hope it is correct so). K10korgac_kill: #! /bin/sh pkill korgac exit 0 Unfortunately this wasn't able to resolve my problem. Maybe my script is wrong. I hope someone can help me. Thanks for your time Max

    Read the article

  • insert xml into sql server

    - by JonDog
    ok, so I know there are a bunch of other post on importing xml to sql server but I just cant seem to figure it out. I think my problem may have to do with having multi-levels. Can anyone help please. My xml, sql table, and the code i've tried. thanks in advance. <items> <item> <sku> <value> the_sku </value> </sku> <short_dis2> <value> short_discription2 <value/> </short_dis2> <short_dis1> <value> short_discription1 </value> </short_dis1> <title> <value> product_title </value> </title> <detailSpec> <value> detailed_specification_html </value> </detailSpec> <basicSpec> <value> basic_overview_html </value> </basicSpec> <basicSpecHeading> <value> besic_spec_heading </value> </basicSpecHeading> <detailSpecHeading> <value> detailed_specifications_heading </value> </detailSpecHeading> <model> <value> the_model_number </value> </model> <image_file_name> <value> the_image_url </value> </image_file_name> </item> ... CREATE TABLE [dbo].[products]( [sku] [nchar](15) NOT NULL, [model] [nvarchar](50) NULL, [title] [ntext] NULL, [short_dis1] [ntext] NULL, [short_dis2] [ntext] NULL, [basicSpecHeading] [ntext] NULL, [basicSpec] [ntext] NULL, [detailSpecHeading] [ntext] NULL, [detailSpec] [ntext] NULL, [image_file_name] [nchar](100) NULL INSERT INTO products (sku, short_dis2,short_dis1,title,detailSpec,basicSpec,basicSpecHeading,detailSpecHeading,model,image_file_name) SELECT X.product.query('sku').value('.', 'nchar(15)'), X.product.query('short_dis2').value('.', 'nvarchar(max)'), X.product.query('short_dis1').value('.', 'nvarchar(max)'), X.product.query('title').value('.', 'nvarchar(max)'), X.product.query('detailSpec').value('.', 'nvarchar(max)'), X.product.query('basicSpec').value('.', 'nvarchar(max)'), X.product.query('basicSpecHeading').value('.', 'nvarchar(max)'), X.product.query('detailSpecHeading').value('.', 'nvarchar(max)'), X.product.query('model').value('.', 'nvarchar(max)'), X.product.query('image_file_name').value('.', 'nvarchar(max)') FROM ( SELECT CAST(x AS XML) FROM OPENROWSET( BULK 'C:\users\me\desktop\xml_sample.xml', SINGLE_BLOB) AS T(x) ) AS T(x) CROSS APPLY x.nodes('Products/Product') AS X(product);

    Read the article

  • SQL SERVER – Weekly Series – Memory Lane – #031

    - by Pinal Dave
    Here is the list of selected articles of SQLAuthority.com across all these years. Instead of just listing all the articles I have selected a few of my most favorite articles and have listed them here with additional notes below it. Let me know which one of the following is your favorite article from memory lane. 2007 Find Table without Clustered Index – Find Table with no Primary Key Clustered index is very important concept for any table. They impact the performance very heavily. Here is a quick script to find tables without a clustered index. Replace TEXT with VARCHAR(MAX) – Stop using TEXT, NTEXT, IMAGE Data Types Question: “Is VARCHAR (MAX) big enough to store the TEXT field?” Answer: “Yes, VARCHAR(MAX) is big enough to accommodate TEXT field. TEXT, NTEXT and IMAGE data types of SQL Server 2000 will be deprecated in a future version of SQL Server, SQL Server 2005 provides backward compatibility to data types but it is recommended to use new data types which are VARHCAR (MAX), NVARCHAR (MAX) and VARBINARY (MAX).” Limiting Result Sets by Using TABLESAMPLE – Examples Introduced in SQL Server 2005, TABLESAMPLE allows you to extract a sampling of rows from a table in the FROM clause. The rows retrieved are random and they are are not in any order. This sampling can be based on a percentage of number of rows. You can use TABLESAMPLE when only a sampling of rows is necessary for the application instead of a full result set. User Defined Functions (UDF) Limitations UDF have its own advantage and usage but in this article we will see the limitation of UDF. Things UDF can not do and why Stored Procedure are considered as more flexible then UDFs. Stored Procedure are more flexibility then User Defined Functions(UDF). However, this blog post is a good read to know what are the limitations of UDF. Change Database Compatible Level – Backward Compatibility For a long time SQL Server stayed on the compatibility level of 80 which is of SQL Server 2000. However, as soon as SQL Server 2005 introduced the issue of compatibility was quite a major issue. Since that time MS has been releasing the versions at every 2-3 years, changing compatibility is a ever popular topic. In this blog post, we learn how we can do the same using T-SQL. We can also do the same using SSMS and here is the blog post for the same: Change Database Compatible Level – Backward Compatibility – Part 2 – Management Studio. Constraint on VARCHAR(MAX) Field To Limit It Certain Length How can I limit the VARCHAR(MAX) field with maximum length of 12500 characters only. His Question was valid as our application was allowed 12500 characters. First of all – this requirement is bit strange but if someone wants to do the same, they can do it as described in this blog post. 2008 UNPIVOT Table Example Understanding UNPIVOT can be very complicated at times. In this blog post, I have attempted to explain the same concept in very simple words. Create Default Constraint Over Table Column A simple straight to script blog post – I still use this blog quite many times for my own reference. UDF – Get the Day of the Week Function It took me 4 iteration to find this very simple function which can immediately get the day of the week in a single line. 2009 Find Hostname and Current Logged In User Name There are two tricks listed in this blog post where users can find out the hostname and current logged user name immediately and very easily. Interesting Observation of Logon Trigger On All Servers When I was doing a project, I made an interesting observation of executing a logon trigger multiple times. It was absolutely unexpected for me! As I was logging only once, naturally, I was expecting the entry only once. However, it did it multiple times on different threads – indeed an eccentric phenomenon at first sight! Difference Between Candidate Keys and Primary Key One needs to be very careful in selecting the Primary Key as an incorrect selection can adversely impact the database architect and future normalization. For a Candidate Key to qualify as a Primary Key, it should be Non-NULL and unique in any domain. I have observed quite often that Primary Keys are seldom changed. I would like to have your feedback on not changing a Primary Key. Create Multiple Filegroup For Single Database Why should one create multiple file group for any database and what are the advantages of the same. In this blog post, I explain the same in detail. List All Objects Created on All Filegroups in Database In this blog post we discuss the essential question – “How can I find which object belongs to which filegroup. Is there any way to know this?” 2010 DATE and TIME in SQL Server 2008 When DATE is converted to DATETIME it adds the of midnight. When TIME is converted to DATETIME it adds the date of 1900 and it is something one wants to consider if you are going to run scripts from SQL Server 2008 to earlier version with CONVERT. Disabled Index and Update Statistics If you do not need a nonclustered index, I suggest you to drop it as keeping them disabled is an overhead on your system. This is because every time the statistics are updated for system all the statistics for disabled indexes are also updated. Precision of SMALLDATETIME – A 1 Minute Precision The precision of the datatype SMALLDATETIME is 1 minute. It discards the seconds by rounding up or rounding down any seconds greater than zero. 2011 Getting Columns Headers without Result Data – SET FMTONLY ON SET FMTONLY ON returns only metadata to the client. It can be used to test the format of the response without actually running the query. When this setting is ON the resultset only have headers of the results but no data. Copy Database from Instance to Another Instance – Copy Paste in SQL Server SQL Server has a feature which copy database from one database to another database and it can be automated as well using SSIS. Make sure you have SQL Server Agent Turned on as this feature will create a job. Puzzle – SELECT * vs SELECT COUNT(*) If you have ever wondered SELECT * gives error when executed alone but SELECT COUNT(*) does not. Why? in that case, you should read this blog post. Creating All New Database with Full Recovery Model This blog post is very based on very interesting story where the user wants to do something by default for every single new database created. Model database is a secret weapon which should be used very carefully and with proper evalution. If used carefully this can be a very much beneficiary when we need a newly created database behave in certain fashion. 2012 In year 2012 I had two interesting series ran on the blog. If there is no fun in learning, the learning becomes a burden. For the same reason, I had decided to build a three part quiz around SEQUENCE. The quiz was to identify the next value of the sequence. I encourage all of you to take part in this fun quiz. Guess the Next Value – Puzzle 1 Guess the Next Value – Puzzle 2 Guess the Next Value – Puzzle 3 Can anyone remember their final day of schooling?  This is probably a silly question because – of course you can!  Many people mark this as the most exciting, happiest day of their life.  It marks the end of testing, the end of following rules set by teachers, and the beginning of finally being able to earn money and work in your chosen field. Read five part series on developer training subject Developer Training - Importance and Significance - Part 1 Developer Training – Employee Morals and Ethics – Part 2 Developer Training – Difficult Questions and Alternative Perspective - Part 3 Developer Training – Various Options for Developer Training – Part 4 Developer Training – A Conclusive Summary- Part 5 Reference: Pinal Dave (http://blog.sqlauthority.com) Filed under: Memory Lane, PostADay, SQL, SQL Authority, SQL Query, SQL Server, SQL Tips and Tricks, T SQL, Technology

    Read the article

  • Shadow mapping with deffered shading for directional lights - shadow map projection problem

    - by Harry
    I'm trying to implement shadow mapping to my engine. I started with directional lights because they seemed to be the easiest one, but I was wrong :) I have implemented deferred shading and I retrieve position from depth. I think that there is the biggest problem but code looks ok for me. Now more about problem: Shadow map projected onto meshes looks bad scaled and translated and also some informations from shadow map texture aren't visible. You can see it on this screen: http://img5.imageshack.us/img5/2254/93dn.png Yelow frustum is light frustum and I have mixed shadow map preview and actual scene. As you can see shadows are in wrong place and shadow of cone and sphere aren't visible. Could you look at my codes and tell me where I have a mistake? // create shadow map if(!_shd)glGenTextures(1, &_shd); glBindTexture(GL_TEXTURE_2D, _shd); glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, 1024, 1024, 0, GL_DEPTH_COMPONENT, GL_FLOAT,NULL); // shadow map size glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, _shd, 0); glDrawBuffer(GL_NONE); // setting camera Vector dire=Vector(0,0,1); ACamera.setLookAt(dire,Vector(0)); ACamera.setPerspectiveView(60.0f,1,0.1f,10.0f); // currently needed for proper frustum corners calculation Vector min(ACamera._point[0]),max(ACamera._point[0]); for(int i=0;i<8;i++){ max=Max(max,ACamera._point[i]); min=Min(min,ACamera._point[i]); } ACamera.setOrthogonalView(min.x,max.x,min.y,max.y,-max.z,-min.z); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, _s_buffer); // framebuffer for shadow map // rendering to depth buffer glBindFramebuffer(GL_DRAW_FRAMEBUFFER, _g_buffer); Shaders["DirLight"].set(true); Matrix4 bias; bias.x.set(0.5,0.0,0.0,0.0); bias.y.set(0.0,0.5,0.0,0.0); bias.z.set(0.0,0.0,0.5,0.0); bias.w.set(0.5,0.5,0.5,1.0); Shaders["DirLight"].set("textureMatrix",ACamera.matrix*Projection3D*bias); // order of multiplications are 100% correct, everything gives mi the same result as using glm glActiveTexture(GL_TEXTURE5); glBindTexture(GL_TEXTURE_2D,_shd); lightDir(dir); // light calculations Vertex Shader makes nothing related to shadow calculatons Pixel shader function which calculates if pixel is in shadow or not: float readShadowMap(vec3 eyeDir) { // retrieve depth of pixel float z = texture2D(depth, gl_FragCoord.xy/screen).z; vec3 pos = vec3(gl_FragCoord.xy/screen, z); // transform by the projection and view inverse vec4 worldSpace = inverse(View)*inverse(ProjectionMatrix)*vec4(pos*2-1,1); worldSpace /= worldSpace.w; vec4 coord=textureMatrix*worldSpace; float vis=1.0f; if(texture2D(shadow, coord.xy).z < coord.z-0.001)vis=0.2f; return vis; } I also have question about shadows specifically for directional light. Currently I always look at 0,0,0 position and in further implementation I have to move light frustum along to camera frustum. I've found how to do this here: http://www.gamedev.net/topic/505893-orthographic-projection-for-shadow-mapping/ but it doesn't give me what I want. Maybe because of problems mentioned above, but I want know your opinion. EDIT: vec4 worldSpace is position read from depht of the scene (not shadow map). Maybe I wasn't precise so I'll try quick explain what is what: View is camera view matrix, ProjectionMatrix is camera projection,. First I try to get world space position from depth map and then multiply it by textureMatrix which is light view *light projection*bias. Rest of code is the same as in many tutorials. I can't use vertex shader to make something like gl_Position=textureMatrix*gl_Vertex and get it interpolated in fragment shader because of deffered rendering use so I want get it from depht buffer. EDIT2: I also tried make it as in Coding Labs tutorial about Shadow Mapping with Deferred Rendering but unfortunately this either works wrong.

    Read the article

  • Creating a CLR UDF with variable number of parameters

    - by josephj1989
    Hi I wanted a function to find the greatest of a list of String values passed in. I want to invoke it as Select greatest('Abcd','Efgh','Zxy','EAD') from sql server. It should return Zxy. The number of parameters is variable.Incidentally it is very similar to oracle GREATEST function. So I wrote a very simple CLR function (Vs2008) and tried to deploy it. See below public partial class UserDefinedFunctions { [Microsoft.SqlServer.Server.SqlFunction] public static SqlString Greatest(params SqlString[] p) { SqlString max=p[0]; foreach (string s in p) max = s.CompareTo(max) > 0 ? s : max; return max; } }; But when I try to compile or deploy it I get the following error Cannot find data type SqlString[]. Is it possible to satisfy my requirement using SQL CLR ?

    Read the article

  • How to select difference using sql?

    - by ganuke
    I wrote a sql query to retrieve data as follows: SELECT (MAX (b.filledqty) - MAX (a.filledqty)) AS filledtoday FROM clientordermas a, clientordermas b WHERE a.clordid = 'w9110126' AND b.clordid = 'w9110126' AND (SELECT max(a.price) FROM clientordermas a WHERE a.clordid = 'w9110126') < 1000; There are three records in the table for the given clordid with price values 800, 900 1200. So, what I need is to get the difference between 1200 and 900 which is 300. But, the above statement always returns 0. What I should get is MAX (b.filledqty) retuns 1200 and MAX (a.filledqty) retuns 900. But it is not happening. This is not the exact problem I am facing but a simplified version of it. Can someone please help?

    Read the article

  • Whats the most efficient MySQL column types for this data?

    - by AlabamaKush
    I have several tables with some pretty standard data in each. Can somebody help me optimize them by telling me the best column types for this data. Whats beside them is what I have currently. Number (max length 7) --> MEDIUMINT(8) Unsigned Text (max length 30) --> VARCHAR(30) Text (max length 200) --> VARCHAR(200) Number (max length 4) --> SMALLINT(5) Unsigned Number (either 0 or 1) --> TINYINT(1) Unsigned Text (max length 500) --> TEXT Any suggestions? I'm just guessing with this so I know some of them are wrong...

    Read the article

  • Which are the most important media queries to use in creating mobile responsive design?

    - by Matt
    There are a lot different media queries for mobile screen sizes. It can be overwhelming to accomodate all of them when designing a responsive mobile site. Which are the most important ones to use when designing for mobile? I found this article that does a pretty good job of outlining the available media queries: http://css-tricks.com/snippets/css/media-queries-for-standard-devices/. /* Smartphones (portrait and landscape) ----------- */ @media only screen and (min-device-width : 320px) and (max-device-width : 480px) { /* Styles */ } /* Smartphones (landscape) ----------- */ @media only screen and (min-width : 321px) { /* Styles */ } /* Smartphones (portrait) ----------- */ @media only screen and (max-width : 320px) { /* Styles */ } /* iPads (portrait and landscape) ----------- */ @media only screen and (min-device-width : 768px) and (max-device-width : 1024px) { /* Styles */ } /* iPads (landscape) ----------- */ @media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) { /* Styles */ } /* iPads (portrait) ----------- */ @media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) { /* Styles */ } /* Desktops and laptops ----------- */ @media only screen and (min-width : 1224px) { /* Styles */ } /* Large screens ----------- */ @media only screen and (min-width : 1824px) { /* Styles */ } /* iPhone 4 ----------- */ @media only screen and (-webkit-min-device-pixel-ratio : 1.5), only screen and (min-device-pixel-ratio : 1.5) { /* Styles */ }

    Read the article

  • facebook messages result set like part 2

    - by David
    Hey guys, I don't think I'm getting it right. Here is my most recent query that I believe is almost working. SELECT max(sender_id) as sender_id, subject, MAX(id) as message_id, MAX(created_at) as updated_at FROM messages where (recipient_id = #{current_user} and recipient_deleted = 'f') or sender_id = #{current_user} GROUP BY subject ORDER BY max(created_at) DESC ; Basically the goal is to fetch all recent messages of a user, group them by subject, and make sure that the photo that is showing up is the other party's photo, never the current user. (also need the most recent message body and message count but that is for another time) Here is what I think is wrong. doing max(sender_id) is wrong, since the current_user id could be higher than the sender's id. I am using the sender_id in the html page to fetch the user's photo.

    Read the article

  • Linq query: append column to query results

    - by jrubengb
    I am trying to figure out how to append a column to Linq query results based on the max value of the query. Essentially, I want to create an EnumerableRowCollection of DataRows that would include a max value record with the same value for each record. So if i have a hundred records returned through the query, I want to next calculate the max value of one of the fields, then append that max value to the original query table: DataTable dt = new DataTable(); dt = myDataSet.myDataTable; EnumerableRowCollection<DataRow> qrySelectRecords = (from d in dt.AsEnumerable() where d.Field<DateTime>("readingDate") >= startDate && g.Field<DateTime>("readingDate") <= endDate select d); Here's where I need help: double maxValue = qrySelectRecords.Field<double>("field1").Max(); foreach (DataRow dr in qrySelectRecords) { qrySelectRecords.Column.Append(maxValue) }

    Read the article

  • Jquery to limit the range of input

    - by Sharvari
    I have a text box that takes input as amount..I want to prevent the user from entering Amount greater than a certain amount..I tried using ajax ..but its not working the way i want..I think jquery wud do the needful..but I am not so good at it..If any one can help?? Ajax function that i Have written: function maxIssue(max, input, iid) { var req = getXMLHTTP(); var strURL = "limit_input.php?max=" + max + "&iid=" + iid; if (input > max) { alert("Issue Failed.Quantity Present in Stock is " + max); } if (input < 0) { alert("Issue Failed.Enter positive Value"); } if (req) { req.onreadystatechange = function() { if (req.readyState == 4) { // only if "OK" if (req.status == 200) { document.getElementById('maxdiv').innerHTML = req.responseText; } else { alert("There was a problem while using XMLHTTP:\n" + req.statusText); } } } } req.open("GET", strURL, true); req.send(null); }

    Read the article

  • MaxTotalSizeInBytes - Blind spots in Usage file and Web Analytics Reports

    - by Gino Abraham
    Originally posted on: http://geekswithblogs.net/GinoAbraham/archive/2013/10/28/maxtotalsizeinbytes---blind-spots-in-usage-file-and-web-analytics.aspx http://blogs.msdn.com/b/sharepoint_strategery/archive/2012/04/16/usage-file-and-web-analytics-reports-with-blind-spots.aspx In my previous post (Troubleshooting SharePoint 2010 Web Analytics), I referenced a problem that can occur when exceeding the daily partition size for the LoggingDB, which generates the ULS message “[Partition] has exceeded the max bytes”. Below, I wanted to provide some additional info on this particular issue and help identify some options if this occurs. As an aside, this post only applies if you are missing portions of Usage data - think blind spots on intermittent days or user activity regularly sparse for the afternoon/evening. If this fits your scenario - read on. But if Usage logs are outright missing, go check out my Troubleshooting post first.  Background on the problem:The LoggingDB database has a default maximum size of ~6GB. However, SharePoint evenly splits this total size into fixed sized logical partitions – and the number of partitions is defined by the number of days to retain Usage data (by default 14 days). In this case, 14 partitions would be created to account for the 14 days of retention. If the retention were halved to 7 days, the LoggingDBwould be split into 7 corresponding partitions at twice the size. In other words, the partition size is generally defined as [max size for DB] / [number of retention days].Going back to the default scenario, the “max size” for the LoggingDB is 6200000000 bytes (~6GB) and the retention period is 14 days. Using our formula, this would be [~6GB] / [14 days], which equates to 444858368 bytes (~425MB) per partition per day. Again, if the retention were halved to 7 days (which halves the number of partitions), the resulting partition size becomes [~6GB] / [7 days], or ~850MB per partition.From my experience, when the partition size for any given day is exceeded, the usage logging for the remainder of the day is essentially thrown away because SharePoint won’t allow any more to be written to that day’s partition. The only clue that this is occurring (beyond truncated usage data) is an error such as the following that gets reported in the ULS:04/08/2012 09:30:04.78    OWSTIMER.EXE (0x1E24)    0x2C98    SharePoint Foundation    Health    i0m6     High    Table RequestUsage_Partition12 has 444858368 bytes that has exceeded the max bytes 444858368It’s also worth noting that the exact bytes reported (e.g. ‘444858368’ above) may slightly vary among farms. For example, you may instead see 445226812, 439123456, or something else in the ballpark. The exact number itself doesn't matter, but this error message intends to indicates that the reporting usage has exceeded the partition size for the given day.What it means:The error itself is easy to miss, which can lead to substantial gaps in the reporting data (your mileage may vary) if not identified. At this point, I can only advise to periodically check the ULS logs for this message. Down the road, I plan to explore if [Developing a Custom Health Rule] could be leveraged to identify the issue (If you've ever built Custom Health Rules, I'd be interested to hear about your experiences). Overcoming this issue also poses a challenge, with workaround options including:Lower the retentionBecause the partition size is generally defined as [max size] / [number of retention days], the first option is to lower the number of days to retain the data – the lower the retention, the lower the divisor and thus a bigger partition. For example, halving the retention from 14 to 7 days would halve the number of partitions, but double the partition size to ~850MB (e.g. [6200000000 bytes] / [7 days] = ~850GB partitions). Lowering it to 2 days would result in two ~3GB partitions… and so on.Recreate the LoggingDB with an increased sizeThe property MaxTotalSizeInBytes is exposed by OM code for the SPUsageDefinition object and can be updated with the example PowerShell snippet below. However, updating this value has no immediate impact because this size only applies when creating a LoggingDB. Therefore, you must create a newLoggingDB for the Usage Service Application. The gotcha: this effectively deletes all prior Usage databecause the Usage Service Application can only have a single LoggingDB.Here is an example snippet to update the "Page Requests" Usage Definition:$def=Get-SPUsageDefinition -Identity "page requests" $def.MaxTotalSizeInBytes=12400000000 $def.update()Create a new Logging database and attach to the Usage Service Application using the following command: Get-spusageapplication | Set-SPUsageApplication -DatabaseServer <dbServer> -DatabaseName <newDBname> Updated (5/10/2012): Once the new database has been created, you can confirm the setting has truly taken by running the following SQL Query (be sure to replace the database name in the following query with the name provided in the PowerShell above)SELECT * FROM [WSS_UsageApplication].[dbo].[Configuration] WITH (nolock) WHERE ConfigName LIKE 'Max Total Bytes - RequestUsage'

    Read the article

  • strange output in ubuntu terminal when running a lex program

    - by Max
    Hi. I'm running a lexical analyzer using lex, and I've got it mostly correct, but my terminal gives strange output once I take out an ECHO statement I was using to help debug the code. With that statement, my output looks like this: max@Max-Ubuntu:~/Desktop/Compiler Project/project2$ ./a.out <../cmmFiles/expression.cmm VOIDID(){ INTID,ID,ID; BOOLID,ID,ID; ID(ID); ID(ID); ID(ID); ID(ID); ID=-ID-NUM+ID/NUM*(-NUM+ID*IDNUM); ID(ID); ID=ID>ID||ID>=ID; IF(ID)ID(NUM);ELSEID(NUM); ID=ID<ID&&ID<=ID; IF(ID==TRUE)ID(NUM);ELSEID(NUM); ID=ID&&!ID||!ID&&ID; IF(ID!=FALSE)ID(NUM);ELSEID(NUM); } While hard to read, that output is correct. Once I take out the ECHO statement, I instead get this: max@Max-Ubuntu:~/Desktop/Compiler Project/project2$ ./a.out <../cmmFiles/expression.cmm }F(ID!=FALSE)ID(NUM);ELSEID(NUM);; It looks like it's only outputting the final line, except with an extraneous } near the beginning, what looks like half an IF token immediately after, and an extraneous ; at the end. Is this some quirk of my terminal, or does removing that ECHO cause my lexer to screw up that badly? I'm hesitant to keep working until I know for sure what's going on here. Thanks for any answers. Here's my lexer: %{ /* definitions of manifest constants -reserved words- BOOL, ELSE, IF, TRUE, WHILE, DO, FALSE, INT, VOID -Punctuation and operators- LPAREN, RPAREN, LBRACK, RBRACK, LBRACE, RBRACE, SEMI, COMMA, PLUS, MINUS, TIMES, DIV, MOD, AND, OR, NOT, IS, ADDR, EQ, NE, LT, GT, LE, GE -Other tokens- NUMBER, ID, PUNCT, OP */ #include <stdio.h> #include <stdlib.h> //#include "y.tab.h" //int line = 1, numAttr; //char *strAttr; %} /* regular definitions */ delim [ \t] ws {delim}+ start "/*" one [^*] two "*" three [^*/] end "/" comment {start}({one}*{two}+{three})*{one}*{two}+{end} letter [A-Za-z] digit [0-9] id ({letter}|_)({letter}|{digit}|_)* number {digit}+ %% {ws} { /*no action and no return */} {comment} { /*no action and no return */} [\n] {ECHO; /*no action */} // <-- this is the ECHO in question. bool { printf("BOOL");} else { printf("ELSE");} if { printf("IF");} true { printf("TRUE");} while { printf("WHILE");} do { printf("DO");} false { printf("FALSE");} int { printf("INT");} void { printf("VOID");} {id} { printf("ID");} {number} { printf("NUM");} "(" { printf("(");} ")" { printf(")");} "[" { printf("[");} "]" { printf("]");} "{" { printf("{");} "}" { printf("}");} ";" { printf(";");} "," { printf(",");} "+" { printf("+");} "-" { printf("-");} "*" { printf("*");} "/" { printf("/");} "%" { printf("%");} "&" { printf("&");} "&&" { printf("&&");} "||" { printf("||");} "!" { printf("!");} "!=" { printf("!=");} "=" { printf("=");} "==" { printf("==");} "<" { printf("<");} "<=" { printf("<=");} ">" { printf(">");} ">=" { printf(">=");} %% int main() { yylex(); printf("\n"); } int yywrap(void) { return 1; } here's the file it's analyzing: /* this program * illustrates evaluation of * arithmetic and boolean * expressions */ void main( ) { int m,n,p; bool a,b,c; scan(m); print(m); scan(n); print(n); p=-m-3+n/2*(-5+m*n%4); print(p); a=m>n || n>=p; if (a) print(1); else print(0); b=m<n && n<=p; if (b==true) print(1); else print(0); c=a && !b || !a && b; if (c!=false) print(1); else print(0); }

    Read the article

  • Having problem with C++ file handling

    - by caramel1991
    Our lecturer has given us a task,I've attempted it and try every single effort I can,but I still struggle with one of the problem in it,here goes the question: The company you work at receives a monthly report in a text format. The report contains the following information. • Department Name • Head of Department Name • Month • Minimum spending of the month • Maximum spending of the month Your program is to obtain the name of the input file from the user. Implement a structure to represent the data: Once the file has been read into your program, print out the following statistics for the user: • List which department has the minimum spending per month by month • List which department has the minimum spending by month by month Write the information into a file called “MaxMin.txt” Then do a processing so that the Department Name, Head of Department Name, Minimum spending and Maximum spending are written to separate files based on the month, eg Jan, Feb, March and so on. and of course our lecturer does send us a text file with the content: Engineering Bill Jan 2000 15000 IT Jack Jan 300 20000 HR Jill Jan 1500 10000 Engineering Bill Feb 5000 45000 IT Jack Feb 4500 7000 HR Jill Feb 5600 60000 Engineering Bill Mar 5000 45000 IT Jack Mar 4500 7000 HR Jill Mar 5600 60000 Engineering Bill Apr 5000 45000 IT Jack Apr 4500 7000 HR Jill Apr 5600 60000 Engineering Bill May 2000 15000 IT Jack May 300 20000 HR Jill May 1500 10000 Engineering Bill Jun 2000 15000 IT Jack Jun 300 20000 HR Jill Jun 1500 10000 and here's the c++ code I've written ue#include include include using namespace std; struct Record { string depName; string head; string month; float max; float min; string name; }myRecord[19]; int main () { string line; ofstream minmax,jan,feb,mar,apr,may,jun; char a[50]; char b[50]; int i = 0,j,k; float temp; //float maxjan=myRecord[0].max,maxfeb=myRecord[0].max,maxmar=myRecord[0].max,maxapr=myRecord[0].max,maxmay=myRecord[0].max,maxjune=myRecord[0].max; float minjan=myRecord[1].min,minfeb=myRecord[1].min,minmar=myRecord[1].min,minapr=myRecord[1].min,minmay=myRecord[1].min,minjune=myRecord[1].min; float maxjan=0,maxfeb=0,maxmar=0,maxapr=0,maxmay=0,maxjune=0; //float minjan=0,minfeb=0,minmar=0,minapr=0,minmay=0,minjune=0; string maxjanDep,maxfebDep,maxmarDep,maxaprDep,maxmayDep,maxjunDep; string minjanDep,minfebDep,minmarDep,minaprDep,minmayDep,minjunDep; cout<<"Enter file name: "; cina; ifstream myfile (a); //minmax.open ("MaxMin.txt"); if (myfile.is_open()){ while (! myfile.eof()){ myfilemyRecord[i].depNamemyRecord[i].headmyRecord[i].monthmyRecord[i].minmyRecord[i].max; cout << myRecord[i].depName<<"\t"< cout<<"Enter file name: "; cinb; ifstream myfile1 (b); minmax.open ("MaxMin.txt"); jan.open ("Jan.txt"); feb.open ("Feb.txt"); mar.open ("March.txt"); apr.open ("April.txt"); may.open ("May.txt"); jun.open ("Jun.txt"); if (myfile1.is_open()){ while (! myfile1.eof()){ myfile1myRecord[i].depNamemyRecord[i].headmyRecord[i].monthmyRecord[i].minmyRecord[i].max; if (myRecord[i].month == "Jan"){ jan<< myRecord[i].depName<<"\t"< if (maxjan< myRecord[i].max){ maxjan=myRecord[i].max; maxjanDep=myRecord[i].depName;} //if (minjan myRecord[i].min){ // minjan=myRecord[i].min; //minjanDep=myRecord[i].depName; //} for (k=1;k<=3;k++){ for (j=0;j<2;j++){ if (myRecord[j].minmyRecord[j+1].min){ temp=myRecord[j].min; myRecord[j].min=myRecord[j+1].min; myRecord[j+1].min=temp; minjanDep=myRecord[j].depName; }}} } if (myRecord[i].month == "Feb"){ feb<< myRecord[i].depName<<"\t"< //if (minfebmyRecord[i].min){ //minfeb=myRecord[i].min; //minfebDep=myRecord[i].depName; //} for (k=1;k<=3;k++){ for (j=0;j<2;j++){ if (myRecord[j].minmyRecord[j+1].min){ temp=myRecord[j].min; myRecord[j].min=myRecord[j+1].min; myRecord[j+1].min=temp; minfebDep=myRecord[j+1].depName; }}} } if (myRecord[i].month == "Mar"){ mar<< myRecord[i].depName<<"\t"< if (myRecord[i].month == "Apr"){ apr<< myRecord[i].depName<<"\t"< if (minaprmyRecord[i].min){ minapr=myRecord[i].min; minaprDep=myRecord[i].min;} } if (myRecord[i].month == "May"){ may< if (minmaymyRecord[i].min){ minmay=myRecord[i].min; minmayDep=myRecord[i].depName;} } if (myRecord[i].month == "Jun"){ jun<< myRecord[i].depName<<"\t"< if (minjunemyRecord[i].min){ minjune=myRecord[i].min; minjunDep=myRecord[i].depName;} } i++; myfile.close(); } minmax<<"department that has maximum spending at jan "< else{ cout << "Unable to open file"< } sorry inside that code ue#include should has iostream along with another two #include fstream and string,but at here it was treated as html tag,so i can't type it. my problem here is,I can't seems to get the minimum spending,I've try all I can but I'm still lingering on it,any idea??THANK YOU!

    Read the article

  • Limiting Number of Characters in a ContentEditable div

    - by Bill Dami
    Hi guys, I am using contenteditable div elements in my web application and I am trying to come up with a solution to limit the amount of characters allowed in the area, and once the limit is hit, attempting to enter characters simply does nothing. This is what I have so far: var content_id = 'editable_div'; //binding keyup/down events on the contenteditable div $('#'+content_id).keyup(function(){ check_charcount(content_id, max); }); $('#'+content_id).keydown(function(){ check_charcount(content_id, max); }); function check_charcount(content_id, max) { if($('#'+content_id).text().length > max) { $('#'+content_id).text($('#'+content_id).text().substring(0, max)); } } This DOES limit the number of characters to the number specified by 'max', however once the area's text is set by the jquery .text() function the cursor resets itself to the beginning of the area. So if the user keeps on typing, the newly entered characters will be inserted at the beginning of the text and the last character of the text will be removed. So really, I just need some way to keep the cursor at the end of the contenteditable area's text.

    Read the article

  • Optimizing MySQL update query

    - by Jernej Jerin
    This is currently my MySQL UPDATE query, which is called from program written in Java: String query = "UPDATE maxday SET DatePressureREL = (SELECT Date FROM ws3600 WHERE PressureREL = (SELECT MAX" + "(PressureREL) FROM ws3600 WHERE Date >= '" + Date + "') AND Date >= '" + Date + "' ORDER BY Date DESC LIMIT 1), " + "PressureREL = (SELECT PressureREL FROM ws3600 WHERE PressureREL = (SELECT MAX(PressureREL) FROM ws3600 " + "WHERE Date >= '" + Date + "') AND Date >= '" + Date + "' ORDER BY Date DESC LIMIT 1), ..."; try { s.execute(query); } catch (SQLException e) { System.out.println("SQL error"); } catch(Exception e) { e.printStackTrace(); } Let me explain first, what does it do. I have two tables, first is ws3600, which holds columns (Date, PressureREL, TemperatureOUT, Dewpoint, ...). Then I have second table, called maxday, which holds columns like DatePressureREL, PressureREL, DateTemperatureOUT, TemperatureOUT,... Now as you can see from an example, I update each column, the question is, is there a faster way? I am asking this, because I am calling MAX twice, first to find the Date for that value and secondly to find the actual value. Now I know that I could write like that: SELECT Date, PressureREL FROM ws3600 WHERE PressureREL = (SELECT MAX(PressureREL) FROM ws3600 WHERE Date >= '" + Date + "') AND Date >= '" + Date + "' ORDER BY Date DESC LIMIT 1 That way I get the Date of the max and the max value at the same time and then update with those values the data in maxday table. But the problem of this solution is, that I have to execute many queries, which as I understand takes alot more time compared to executing one long mysql query because of overhead in sending each query to the server. If there is no better way, which solution beetwen this two should I choose. The first, which only takes one query but is very unoptimized or the second which is beter in terms of optimization, but needs alot more queries which probably means that the preformance gain is lost because of overhead in sending each query to the server?

    Read the article

  • Returning recursive ternary freaks out

    - by David Titarenco
    Hi, assume this following function: int binaryTree::findHeight(node *n) { if (n == NULL) { return 0; } else { return 1 + max(findHeight(n->left), findHeight(n->right)); } } Pretty standard recursive treeHeight function for a given binary search tree binaryTree. Now, I was helping a friend (he's taking an algorithms course), and I ran into some weird issue with this function that I couldn't 100% explain to him. With max being defined as max(a,b) ((a)>(b)?(a):(b)) (which happens to be the max definition in windef.h), the recursive function freaks out (it runs something like n^n times where n is the tree height). This obviously makes checking the height of a tree with 3000 elements take very, very long. However, if max is defined via templating, like std does it, everything is okay. So using std::max fixed his problem. I just want to know why. Also, why does the countLeaves function work fine, using the same programmatic recursion? int binaryTree::countLeaves(node *n) { if (n == NULL) { return 0; } else if (n->left == NULL && n->right == NULL) { return 1; } else { return countLeaves(n->left) + countLeaves(n->right); } } Is it because in returning the ternary function, the values a => countLeaves(n->left) and b => countLeaves(n->right) were recursively double called simply because they were the resultants? Thank you!

    Read the article

  • RANDOM Number Generation in C

    - by CVS-2600Hertz-wordpress-com
    Recently i have begun development of a simple game. It is improved version of an earlier version that i had developed. Large part of the game's success depends on Random number generation in different modes: MODE1 - Truly Random mode myRand(min,max,mode=1); Should return me a random integer b/w min & max. MODE2 - Pseudo Random : Token out of a bag mode myRand(min,max,mode=2); Should return me a random integer b/w min & max. Also should internally keep track of the values returned and must not return the same value again until all the other values are returned atleast once. MODE3 - Pseudo Random : Human mode myRand(min,max,mode=3); Should return me a random integer b/w min & max. The randomisation ought to be not purely mathematically random, rather random as user perceive it. How Humans see RANDOM. * Assume the code is time-critical (i.e. any performance optimisations are welcome) * Pseudo-code will do but an implementation in C is what i'm looking for. * Please keep it simple. A single function should be sufficient (thats what i'm looking for) Thank You

    Read the article

  • help with mysql triggers (checking values before insert)

    - by user332817
    hi I'm quite new to mysql and I'm trying to figure out how to use triggers. what I'm trying to do: I have 2 tables, max and sub_max, when I insert a new row to sub_max I want to check if the SUM of the values with the same foreign_key as the new row are less than the value in the max table. I think this sounds confusing so here are my tables: CREATE TABLE max( number INT , MaxAmount integer NOT NULL) CREATE TABLE sub_max( sub_number INT , sub_MaxAmount integer NOT NULL, number INT, FOREIGN KEY ( number ) REFERENCES max( number )) and here is my code for the trigger, I know the syntax is off but this is the best I could do from looking up tutorials. CREATE TRIGGER maxallowed after insert on submax FOR EACH ROW BEGIN DECLARE submax integer; DECLARE maxmax integer; submax = select sum(sub_MaxAmount) from sub_max where sub_number = new.sub_number; submax = submax + new. sub_MaxAmount; maxmax = select MaxAmount from max where number = new.number ; if max>maxmax rollback? END I wanted to know if I'm doing this remotely correctly. Thanks in advance.

    Read the article

< Previous Page | 20 21 22 23 24 25 26 27 28 29 30 31  | Next Page >