Search Results

Search found 140 results on 6 pages for 'tinyint'.

Page 3/6 | < Previous Page | 1 2 3 4 5 6  | Next Page >

  • IsNumeric() Broken? Only up to a point.

    - by Phil Factor
    In SQL Server, probably the best-known 'broken' function is poor ISNUMERIC() . The documentation says 'ISNUMERIC returns 1 when the input expression evaluates to a valid numeric data type; otherwise it returns 0. ISNUMERIC returns 1 for some characters that are not numbers, such as plus (+), minus (-), and valid currency symbols such as the dollar sign ($).'Although it will take numeric data types (No, I don't understand why either), its main use is supposed to be to test strings to make sure that you can convert them to whatever numeric datatype you are using (int, numeric, bigint, money, smallint, smallmoney, tinyint, float, decimal, or real). It wouldn't actually be of much use anyway, since each datatype has different rules. You actually need a RegEx to do a reasonably safe check. The other snag is that the IsNumeric() function  is a bit broken. SELECT ISNUMERIC(',')This cheerfully returns 1, since it believes that a comma is a currency symbol (not a thousands-separator) and you meant to say 0, in this strange currency.  However, SELECT ISNUMERIC(N'£')isn't recognized as currency.  '+' and  '-' is seen to be numeric, which is stretching it a bit. You'll see that what it allows isn't really broken except that it doesn't recognize Unicode currency symbols: It just tells you that one numeric type is likely to accept the string if you do an explicit conversion to it using the string. Both these work fine, so poor IsNumeric has to follow suit. SELECT  CAST('0E0' AS FLOAT)SELECT  CAST (',' AS MONEY) but it is harder to predict which data type will accept a '+' sign. SELECT  CAST ('+' AS money) --0.00SELECT  CAST ('+' AS INT)   --0SELECT  CAST ('+' AS numeric)/* Msg 8115, Level 16, State 6, Line 4 Arithmetic overflow error converting varchar to data type numeric.*/SELECT  CAST ('+' AS FLOAT)/*Msg 8114, Level 16, State 5, Line 5Error converting data type varchar to float.*/> So we can begin to say that the maybe IsNumeric isn't really broken, but is answering a silly question 'Is there some numeric datatype to which i can convert this string? Almost, but not quite. The bug is that it doesn't understand Unicode currency characters such as the euro or franc which are actually valid when used in the CAST function. (perhaps they're delaying fixing the euro bug just in case it isn't necessary).SELECT ISNUMERIC (N'?23.67') --0SELECT  CAST (N'?23.67' AS money) --23.67SELECT ISNUMERIC (N'£100.20') --1SELECT  CAST (N'£100.20' AS money) --100.20 Also the CAST function itself is quirky in that it cannot convert perfectly reasonable string-representations of integers into integersSELECT ISNUMERIC('200,000')       --1SELECT  CAST ('200,000' AS INT)   --0/*Msg 245, Level 16, State 1, Line 2Conversion failed when converting the varchar value '200,000' to data type int.*/  A more sensible question is 'Is this an integer or decimal number'. This cuts out a lot of the apparent quirkiness. We do this by the '+E0' trick. If we want to include floats in the check, we'll need to make it a bit more complicated. Here is a small test-rig. SELECT  PossibleNumber,         ISNUMERIC(CAST(PossibleNumber AS NVARCHAR(20)) + 'E+00') AS Hack,        ISNUMERIC (PossibleNumber + CASE WHEN PossibleNumber LIKE '%E%'                                          THEN '' ELSE 'E+00' END) AS Hackier,        ISNUMERIC(PossibleNumber) AS RawIsNumericFROM    (SELECT CAST(',' AS NVARCHAR(10)) AS PossibleNumber          UNION SELECT '£' UNION SELECT '.'         UNION SELECT '56' UNION SELECT '456.67890'         UNION SELECT '0E0' UNION SELECT '-'         UNION SELECT '-' UNION SELECT '.'         UNION  SELECT N'?' UNION SELECT N'¢'        UNION  SELECT N'?' UNION SELECT N'?34.56'         UNION SELECT '-345' UNION SELECT '3.332228E+09') AS examples Which gives the result ... PossibleNumber Hack Hackier RawIsNumeric-------------- ----------- ----------- ------------? 0 0 0- 0 0 1, 0 0 1. 0 0 1¢ 0 0 1£ 0 0 1? 0 0 0?34.56 0 0 00E0 0 1 13.332228E+09 0 1 1-345 1 1 1456.67890 1 1 156 1 1 1 I suspect that this is as far as you'll get before you abandon IsNumeric in favour of a regex. You can only get part of the way with the LIKE wildcards, because you cannot specify quantifiers. You'll need full-blown Regex strings like these ..[-+]?\b[0-9]+(\.[0-9]+)?\b #INT or REAL[-+]?\b[0-9]{1,3}\b #TINYINT[-+]?\b[0-9]{1,5}\b #SMALLINT.. but you'll get even these to fail to catch numbers out of range.So is IsNumeric() an out and out rogue function? Not really, I'd say, but then it would need a damned good lawyer.

    Read the article

  • System.Data.SQLite parameter issue

    - by CasperT
    I have the following code: try { //Create connection SQLiteConnection conn = DBConnection.OpenDB(); //Verify user input, normally you give dbType a size, but Text is an exception var uNavnParam = new SQLiteParameter("@uNavnParam", SqlDbType.Text) { Value = uNavn }; var bNavnParam = new SQLiteParameter("@bNavnParam", SqlDbType.Text) { Value = bNavn }; var passwdParam = new SQLiteParameter("@passwdParam", SqlDbType.Text) {Value = passwd}; var pc_idParam = new SQLiteParameter("@pc_idParam", SqlDbType.TinyInt) { Value = pc_id }; var noterParam = new SQLiteParameter("@noterParam", SqlDbType.Text) { Value = noter }; var licens_idParam = new SQLiteParameter("@licens_idParam", SqlDbType.TinyInt) { Value = licens_id }; var insertSQL = new SQLiteCommand("INSERT INTO Brugere (navn, brugernavn, password, pc_id, noter, licens_id)" + "VALUES ('@uNameParam', '@bNavnParam', '@passwdParam', '@pc_idParam', '@noterParam', '@licens_idParam')", conn); insertSQL.Parameters.Add(uNavnParam); //replace paramenter with verified userinput insertSQL.Parameters.Add(bNavnParam); insertSQL.Parameters.Add(passwdParam); insertSQL.Parameters.Add(pc_idParam); insertSQL.Parameters.Add(noterParam); insertSQL.Parameters.Add(licens_idParam); insertSQL.ExecuteNonQuery(); //Execute query //Close connection DBConnection.CloseDB(conn); //Let the user know that it was changed succesfully this.Text = "Succes! Changed!"; } catch(SQLiteException e) { //Catch error MessageBox.Show(e.ToString(), "ALARM"); } It executes perfectly, but when I view my "brugere" table, it has inserted the values: '@uNameParam', '@bNavnParam', '@passwdParam', '@pc_idParam', '@noterParam', '@licens_idParam' literally. Instead of replacing them. I have tried making a breakpoint and checked the parameters, they do have the correct assigned values. So that is not the issue either. I have been tinkering with this a lot now, with no luck, can anyone help? Oh and for reference, here is the OpenDB method from the DBConnection class: public static SQLiteConnection OpenDB() { try { //Gets connectionstring from app.config const string myConnectString = "data source=data;"; var conn = new SQLiteConnection(myConnectString); conn.Open(); return conn; } catch (SQLiteException e) { MessageBox.Show(e.ToString(), "ALARM"); return null; } }

    Read the article

  • sql: Group by x,y,z; return grouped by x,y with lowest f(z)

    - by Sai Emrys
    This is for http://cssfingerprint.com I collect timing stats about how fast the different methods I use perform on different browsers, etc., so that I can optimize the scraping speed. Separately, I have a report about what each method returns for a handful of URLs with known-correct values, so that I can tell which methods are bogus on which browsers. (Each is different, alas.) The related tables look like this: CREATE TABLE `browser_tests` ( `id` int(11) NOT NULL AUTO_INCREMENT, `bogus` tinyint(1) DEFAULT NULL, `result` tinyint(1) DEFAULT NULL, `method` varchar(255) DEFAULT NULL, `url` varchar(255) DEFAULT NULL, `os` varchar(255) DEFAULT NULL, `browser` varchar(255) DEFAULT NULL, `version` varchar(255) DEFAULT NULL, `created_at` datetime DEFAULT NULL, `updated_at` datetime DEFAULT NULL, `user_agent` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=33784 DEFAULT CHARSET=latin1 CREATE TABLE `method_timings` ( `id` int(11) NOT NULL AUTO_INCREMENT, `method` varchar(255) DEFAULT NULL, `batch_size` int(11) DEFAULT NULL, `timing` int(11) DEFAULT NULL, `os` varchar(255) DEFAULT NULL, `browser` varchar(255) DEFAULT NULL, `version` varchar(255) DEFAULT NULL, `user_agent` varchar(255) DEFAULT NULL, `created_at` datetime DEFAULT NULL, `updated_at` datetime DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=28849 DEFAULT CHARSET=latin1 (user_agent is broken down pre-insert into browser, version, and os from a small list of recognized values using regex; I keep the original user-agent string just in case.) I have a query like this that tells me the average timing for every non-bogus browser / version / method tuple: select c, avg(bogus) as bog, timing, method, browser, version from browser_tests as b inner join ( select count(*) as c, round(avg(timing)) as timing, method, browser, version from method_timings group by browser, version, method having c > 10 order by browser, version, timing ) as t using (browser, version, method) group by browser, version, method having bog < 1 order by browser, version, timing; Which returns something like: c bog tim method browser version 88 0.8333 184 reuse_insert Chrome 4.0.249.89 18 0.0000 238 mass_insert_width Chrome 4.0.249.89 70 0.0400 246 mass_insert Chrome 4.0.249.89 70 0.0400 327 mass_noinsert Chrome 4.0.249.89 88 0.0556 367 reuse_reinsert Chrome 4.0.249.89 88 0.0556 383 jquery Chrome 4.0.249.89 88 0.0556 863 full_reinsert Chrome 4.0.249.89 187 0.0000 105 jquery Chrome 5.0.307.11 187 0.8806 109 reuse_insert Chrome 5.0.307.11 123 0.0000 110 mass_insert_width Chrome 5.0.307.11 176 0.0000 231 mass_noinsert Chrome 5.0.307.11 176 0.0000 237 mass_insert Chrome 5.0.307.11 187 0.0000 314 reuse_reinsert Chrome 5.0.307.11 187 0.0000 372 full_reinsert Chrome 5.0.307.11 12 0.7500 82 reuse_insert Chrome 5.0.335.0 12 0.2500 102 jquery Chrome 5.0.335.0 [...] I want to modify this query to return only the browser/version/method with the lowest timing - i.e. something like: 88 0.8333 184 reuse_insert Chrome 4.0.249.89 187 0.0000 105 jquery Chrome 5.0.307.11 12 0.7500 82 reuse_insert Chrome 5.0.335.0 [...] How can I do this, while still returning the method that goes with that lowest timing? I could filter it app-side, but I'd rather do this in mysql since it'd work better with my caching.

    Read the article

  • java.sql.SQLException: Parameter number X is not an OUT parameter

    - by Frederik
    Hi guys, I'm struggling with getting the result OUT variable from a MySQL stored procedure. I get the following error: java.sql.SQLException: Parameter number 3 is not an OUT parameter The stored procedure looks like this: CREATE DEFINER=`cv_admin`@`localhost` PROCEDURE `CheckGameEligibility`( IN gID INT(10), IN uID INT(10), OUT result TINYINT(1) ) BEGIN # Do lots of stuff, then eventually: SET result = 1; END My java function takes an array of strings* and creates the CallableStatement object dynamically: public static int callAndReturnResult( String sql , String[] values ) { int out = 0 ; try { // construct the SQL. Creates: CheckGameEligibility(?, ?, ?) sql += "(" ; for( int i = 0 ; i < values.length ; i++ ) { sql += "?, " ; } sql += "?)" ; System.out.println( "callAndReturnResult("+sql+"): constructed SQL: " + sql ); // Then the statement CallableStatement cstmt = DB.prepareCall( sql ); for( int i = 0 ; i < values.length ; i++ ) { System.out.println( " " + (i+1) + ": " + values[ i ] ) ; cstmt.setString(i+1, values[ i ] ); } System.out.println( " " + (values.length+1) + ": ? (OUT)" ) ; cstmt.registerOutParameter( values.length + 1 , Types.TINYINT ); cstmt.execute(); out = cstmt.getInt( values.length ); cstmt.close(); } catch( Exception e ) { System.out.println( "*** db trouble: callAndReturnResult(" + sql + " failed: " + e ); e.printStackTrace() ; } return out ; } *) I suppose I should be using an int array instead of a string array, but it doesn't seem to be what the error message was about. Anyway, here's the output it generates: callAndReturnResult(CheckGameEligibility(?, ?, ?)): constructed SQL: CheckGameEligibility(?, ?, ?) 1: 57 2: 29 3: ? (OUT) *** db trouble: callAndReturnResult(CheckGameEligibility(?, ?, ?) failed: java.sql.SQLException: Parameter number 3 is not an OUT parameter at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1075) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:989) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:984) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:929) at com.mysql.jdbc.CallableStatement.checkIsOutputParam(CallableStatement.java:692) at com.mysql.jdbc.CallableStatement.registerOutParameter(CallableStatement.java:1847) at org.apache.commons.dbcp.DelegatingCallableStatement.registerOutParameter(DelegatingCallabl>eStatement.java:92) at Tools.callAndReturnResult(Tools.java:156) Any ideas what might be the problem? :) Thanks in advance!

    Read the article

  • mysql enum performance: is enum slower than INT

    - by JP19
    Hi, Is it better to have a field status enum('active', 'hidden', 'deleted') OR status tinyint(3) with a lookup table. Assume that status can take only one value at a time. In particular, I am interested in knowing, are operations on enum significantly slower than or as fast as operations on int ? There is a related question on SO Mysql: enum confusion but i) It does not discuss performance at all ii) There is very little explanation on WHY one approach is better than the other. regards, JP

    Read the article

  • Under what circumstances would a LINQ-to-SQL Entity "lose" a changed field?

    - by John Rudy
    I'm going nuts over what should be a very simple situation. In an ASP.NET MVC 2 app (not that I think this matters), I have an edit action which takes a very small entity and makes a few changes. The key portion (outside of error handling/security) looks like this: Todo t = Repository.GetTodoByID(todoID); UpdateModel(t); Repository.Save(); Todo is the very simple, small entity with the following fields: ID (primary key), FolderID (foreign key), PercentComplete, TodoText, IsDeleted and SaleEffortID (foreign key). Each of these obviously corresponds to a field in the database. When UpdateModel(t) is called, t does get correctly updated for all fields which have changed. When Repository.Save() is called, by the time the SQL is written out, FolderID reverts back to its original value. The complete code to Repository.Save(): public void Save() { myDataContext.SubmitChanges(); } myDataContext is an instance of the DataContext class created by the LINQ-to-SQL designer. Nothing custom has been done to this aside from adding some common interfaces to some of the entities. I've validated that the FolderID is getting lost before the call to Repository.Save() by logging out the generated SQL: UPDATE [Todo].[TD_TODO] SET [TD_PercentComplete] = @p4, [TD_TodoText] = @p5, [TD_IsDeleted] = @p6 WHERE ([TD_ID] = @p0) AND ([TD_TDF_ID] = @p1) AND /* Folder ID */ ([TD_PercentComplete] = @p2) AND ([TD_TodoText] = @p3) AND (NOT ([TD_IsDeleted] = 1)) AND ([TD_SE_ID] IS NULL) /* SaleEffort ID */ -- @p0: Input BigInt (Size = -1; Prec = 0; Scale = 0) [5] -- @p1: Input BigInt (Size = -1; Prec = 0; Scale = 0) [1] /* this SHOULD be 4 and in the update list */ -- @p2: Input TinyInt (Size = -1; Prec = 0; Scale = 0) [90] -- @p3: Input NVarChar (Size = 4000; Prec = 0; Scale = 0) [changing text] -- @p4: Input TinyInt (Size = -1; Prec = 0; Scale = 0) [0] -- @p5: Input NVarChar (Size = 4000; Prec = 0; Scale = 0) [changing text foo] -- @p6: Input Bit (Size = -1; Prec = 0; Scale = 0) [True] -- Context: SqlProvider(Sql2005) Model: AttributedMetaModel Build: 4.0.30319.1 So somewhere between UpdateModel(t) (where I've validated in the debugger that FolderID updated) and the output of this SQL, the FolderID reverts. The other fields all save. (Well, OK, I haven't validated SaleEffortID yet, because that subsystem isn't really ready yet, but everything else saves.) I've exhausted my own means of research on this: Does anyone know of conditions which would cause a partial entity reset (EG, something to do with long foreign keys?), and/or how to work around this?

    Read the article

  • Byte to Integer in c#

    - by jtb
    I am reading a row from a SQL Server table. One of the columns is of type tinyint. I want to get the value into an int or int32 variable. rdr.GetByte(j) (byte) rdr.GetValue(j) ...seems to be the only way to retrieve the value. But I can't figure out how to get the result into an int var.

    Read the article

  • Are there drawbacks to altering MySQL table data types?

    - by Tower
    Hi, I'm wondering that how much worried I should be about data types. I can easily jump from TINYINT to SMALLINT and from SMALLINT to INT, but are there any drawbacks to this? Obviously situations like from text to int will have consequences, but I'm talking about situations like INT-BIGINT, TINYTEXT-TEXT, etc.

    Read the article

  • 4 table query / join. getting duplicate rows

    - by Horse
    So I have written a query that will grab an order (this is for an ecommerce type site), and from that order id it will get all order items (ecom_order_items), print options (c_print_options) and images (images). The eoi_p_id is currently a foreign key from the images table. This works fine and the query is: SELECT eoi_parentid, eoi_p_id, eoi_po_id, eoi_quantity, i_id, i_parentid, po_name, po_price FROM ecom_order_items, images, c_print_options WHERE eoi_parentid = '1' AND i_id = eoi_p_id AND po_id = eoi_po_id; The above would grab all the stuff I need for order #1 Now to complicate things I added an extra table (ecom_products), which needs to act in a similar way to the images table. The eoi_p_id can also point at a foreign key in this table too. I have added an extra field 'eoi_type' which will either have the value 'image', or 'product'. Now items in the order could be made up of a mix of items from images or ecom_products. Whatever I try it either ends up with too many records, wont actually output any with eoi_type = 'product', and just generally wont work. Any ideas on how to achieve what I am after? Can provide SQL samples if needed? SELECT eoi_id, eoi_parentid, eoi_p_id, eoi_po_id, eoi_po_id_2, eoi_quantity, eoi_type, i_id, i_parentid, po_name, po_price, po_id, ep_id FROM ecom_order_items, images, c_print_options, ecom_products WHERE eoi_parentid = '9' AND i_id = eoi_p_id AND po_id = eoi_po_id The above outputs duplicate rows and doesnt work as expected. Am I going about this the wrong way? Should I have seperate foreign key fields for the eoi_p_id depending it its an image or a product? Should I be using JOINs? Here is a mysql explain of the tables in question ecom_products +-------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------+--------------+------+-----+---------+----------------+ | ep_id | int(8) | NO | PRI | NULL | auto_increment | | ep_title | varchar(255) | NO | | NULL | | | ep_link | text | NO | | NULL | | | ep_desc | text | NO | | NULL | | | ep_imgdrop | text | NO | | NULL | | | ep_price | decimal(6,2) | NO | | NULL | | | ep_category | varchar(255) | NO | | NULL | | | ep_hide | tinyint(1) | NO | | 0 | | | ep_featured | tinyint(1) | NO | | 0 | | +-------------+--------------+------+-----+---------+----------------+ ecom_order_items +--------------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------------+-------------+------+-----+---------+----------------+ | eoi_id | int(8) | NO | PRI | NULL | auto_increment | | eoi_parentid | int(8) | NO | | NULL | | | eoi_type | varchar(32) | NO | | NULL | | | eoi_p_id | int(8) | NO | | NULL | | | eoi_po_id | int(8) | NO | | NULL | | | eoi_quantity | int(4) | NO | | NULL | | +--------------+-------------+------+-----+---------+----------------+ c_print_options +------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------+--------------+------+-----+---------+----------------+ | po_id | int(8) | NO | PRI | NULL | auto_increment | | po_name | varchar(255) | NO | | NULL | | | po_price | decimal(6,2) | NO | | NULL | | +------------+--------------+------+-----+---------+----------------+ images +--------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------------+--------------+------+-----+---------+----------------+ | i_id | int(8) | NO | PRI | NULL | auto_increment | | i_filename | varchar(255) | NO | | NULL | | | i_data | longtext | NO | | NULL | | | i_parentid | int(8) | NO | | NULL | | +--------------+--------------+------+-----+---------+----------------+

    Read the article

  • MySQL: SUM in WHERE clause

    - by checcco
    Hi guys, I've got this table CREATE TABLE `subevents` ( `id` int(11) NOT NULL AUTO_INCREMENT, `title` varchar(150) DEFAULT NULL, `content` text, `class` tinyint(4) NOT NULL DEFAULT '1', PRIMARY KEY (`id`) ) ENGINE=MyISAM Each row can have a different value in the 'class' field. I'd like to select any number of rows, ordered randomly, as long as the sum of the values in the 'class' field is equal to 100. How could I accomplish it directly in the MySQL query without doing it later in PHP? Thanks everybody!

    Read the article

  • Simple UPDATE query with (sometime) long query times

    - by Eric
    I run a dedicated MySQL server (2 cores, 16GB RAM) serving 100-200 requests per second. It is getting sluggish during peak traffic and I have a hard time optimizing the server. So I'm looking for some ideas now that I have done lots of Innodb fine-tuning with the "TUNING PRIMER" The query that now generates most slow queries is the following (see result from mysqldumpslow): Count: 433 Time=3.40s (1470s) Lock=0.00s (0s) Rows=0.0 (0), UPDATE user_sessions SET tid='S' WHERE idsession='S' I am very surprised to have so many long queries for such a simple query with no locking. Fyi, the table is InnoDB and has 14000 rows. It contains all active sessions on the site with approx 10 UPDATE and SELECT hits per second. Here is its structure: CREATE TABLE `user_sessions` ( `personid` mediumint(9) NOT NULL DEFAULT '0', `ip` varchar(18) COLLATE utf8_unicode_ci NOT NULL, `idsession` varchar(32) COLLATE utf8_unicode_ci NOT NULL, `datum` date NOT NULL DEFAULT '0000-00-00', `tid` time NOT NULL DEFAULT '00:00:00', `status` tinyint(4) NOT NULL DEFAULT '0', KEY `personid` (`personid`), KEY `idsession` (`idsession`), KEY `datum` (`datum`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci Any ideas?

    Read the article

  • SQL Authority News – Download SQL Server Data Type Conversion Chart

    - by pinaldave
    Datatypes are very important concepts of SQL Server and there are quite often need to convert them from one datatypes to another datatype. I have seen that deveoper often get confused when they have to convert the datatype. There are two important concept when it is about datatype conversion. Implicit Conversion: Implicit conversions are those conversions that occur without specifying either the CAST or CONVERT function. Explicit Conversions: Explicit conversions are those conversions that require the CAST or CONVERT function to be specified. What it means is that if you are trying to convert value from datetime2 to time or from tinyint to int, SQL Server will automatically convert (implicit conversation) for you. However, if you are attempting to convert timestamp to smalldatetime or datetime to int you will need to explicitely convert them using either CAST or CONVERT function as well appropriate parameters. Let us see a quick example of Implict Conversion and Explict Conversion. Implicit Conversion: Explicit Conversion: You can see from above example that how we need both of the types of conversion in different situation. There are so many different datatypes and it is humanly impossible to know which datatype require implicit and which require explicit conversion. Additionally there are cases when the conversion is not possible as well. Microsoft have published a chart where the grid displays various conversion possibilities as well a quick guide. Download SQL Server Data Type Conversion Chart Reference: Pinal Dave (http://blog.sqlauthority.com) Filed under: PostADay, SQL, SQL Authority, SQL Download, SQL Query, SQL Server, SQL Tips and Tricks, T SQL, Technology

    Read the article

  • Grouping a comma separated value on common data [closed]

    - by Ankit
    I have a table with col1 id int, col2 as varchar (comma separated values) and column 3 for assigning group to them. Table looks like col1 col2 group .............................. 1 2,3,4 2 5,6 3 1,2,5 4 7,8 5 11,3 6 22,8 This is only the sample of real data, now I have to assign a group no to them in such a way that output looks like col1 col2 group .............................. 1 2,3,4 1 2 5,6 1 3 1,2,5 1 4 7,8 2 5 11,3 1 6 22,8 2 The logic for assigning group no is that every similar comma separated value of string in col2 have to be same group no as every where in col2 where '2' is there it has to be same group no but the complication is that 2,3,4 are together so they all three int value if found in any where in col2 will be assigned same group. The major part is 2,3,4 and 1,2,5 both in col2 have 2 so all int 1,2,3,4,5 have to assign same group no. Tried store procedure with match against on col2 but not getting desired result Most imp (I can't use normalization, because I can't afford to make new table from my original table which have millions of records), even normalization is not helpful in my context. This question is also on stackoverflow with bounty on this link Achieved so far:- I have set the group column auto increment and then wrote this procedure:- BEGIN declare cil1_new,col2_new,group_new int; declare done tinyint default 0; declare group_new varchar(100); declare cur1 cursor for select col1,col2,`group` from company ; DECLARE CONTINUE HANDLER FOR NOT FOUND SET done=1; open cur1; REPEAT fetch cur1 into col1_new,col2_new,group_new; update company set group=group_new where match(col2) against(concat("'",col2_new,"'")); until done end repeat; close cur1; select * from company; END This procedure is working, no syntax mistake but the problem is that I am not achieving the desired result exactly.

    Read the article

  • MySQL: Creating table with FK error (errno 150)

    - by Peter Bailey
    I've tried searching on this error and nothing I've found helps me, so I apologize in advance if this is a duplicate and I'm just too dumb to find it. I've created a model with MySQL Workbench and am now attempting to install it to a mysql server. Using File Export Forward Engineer SQL CREATE Script... it outputs a nice big file for me, with all the settings I ask for. I switch over to MySQL GUI Tools (the Query Browser specifically) and load up this script (note that I'm going form one official MySQL tool to another). However, when I try to actually execute this file, I get the same error over and over SQLSTATE[HY000]: General error: 1005 Can't create table './srs_dev/location.frm' (errno: 150) "OK", I say to myself, something is wrong with the location table. So I check out the definition in the output file. SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0; SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0; SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL'; -- ----------------------------------------------------- -- Table `state` -- ----------------------------------------------------- DROP TABLE IF EXISTS `state` ; CREATE TABLE IF NOT EXISTS `state` ( `state_id` INT NOT NULL AUTO_INCREMENT , `iso_3166_2_code` VARCHAR(2) NOT NULL , `name` VARCHAR(60) NOT NULL , PRIMARY KEY (`state_id`) ) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `brand` -- ----------------------------------------------------- DROP TABLE IF EXISTS `brand` ; CREATE TABLE IF NOT EXISTS `brand` ( `brand_id` INT UNSIGNED NOT NULL AUTO_INCREMENT , `name` VARCHAR(45) NOT NULL , `domain` VARCHAR(45) NOT NULL , `manager_name` VARCHAR(100) NULL , `manager_email` VARCHAR(255) NULL , PRIMARY KEY (`brand_id`) ) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `location` -- ----------------------------------------------------- DROP TABLE IF EXISTS `location` ; CREATE TABLE IF NOT EXISTS `location` ( `location_id` INT UNSIGNED NOT NULL AUTO_INCREMENT , `name` VARCHAR(255) NOT NULL , `address_line_1` VARCHAR(255) NULL , `address_line_2` VARCHAR(255) NULL , `city` VARCHAR(100) NULL , `state_id` TINYINT UNSIGNED NULL DEFAULT NULL , `postal_code` VARCHAR(10) NULL , `phone_number` VARCHAR(20) NULL , `fax_number` VARCHAR(20) NULL , `lat` DECIMAL(9,6) NOT NULL , `lng` DECIMAL(9,6) NOT NULL , `contact_url` VARCHAR(255) NULL , `brand_id` TINYINT UNSIGNED NOT NULL , `summer_hours` VARCHAR(255) NULL , `winter_hours` VARCHAR(255) NULL , `after_hours_emergency` VARCHAR(255) NULL , `image_file_name` VARCHAR(100) NULL , `manager_name` VARCHAR(100) NULL , `manager_email` VARCHAR(255) NULL , `created_date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP , PRIMARY KEY (`location_id`) , CONSTRAINT `fk_location_state` FOREIGN KEY (`state_id` ) REFERENCES `state` (`state_id` ) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_location_brand` FOREIGN KEY (`brand_id` ) REFERENCES `brand` (`brand_id` ) ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE = InnoDB; CREATE INDEX `fk_location_state` ON `location` (`state_id` ASC) ; CREATE INDEX `fk_location_brand` ON `location` (`brand_id` ASC) ; CREATE INDEX `idx_lat` ON `location` (`lat` ASC) ; CREATE INDEX `idx_lng` ON `location` (`lng` ASC) ; Looks ok to me. I surmise that maybe something is wrong with the Query Browser, so I put this file on the server and try to load it this way ] mysql -u admin -p -D dbname < path/to/create_file.sql And I get the same error. So I start to Google this issue and find all kinds of accounts that talk about an error with InnoDB style tables that fail with foreign keys, and the fix is to add "SET FOREIGN_KEY_CHECKS=0;" to the SQL script. Well, as you can see, that's already part of the file that MySQL Workbench spat out. So, my question is then, why is this not working when I'm doing what I think I'm supposed to be doing? Version Info: # MySQL: 5.0.45 GUI Tools: 1.2.17 Workbench: 5.0.30

    Read the article

  • How can I optimize this subqueried and Joined MySQL Query?

    - by kevzettler
    I'm pretty green on mysql and I need some tips on cleaning up a query. It is used in several variations through out a site. Its got some subquerys derived tables and fun going on. Heres the query: # Query_time: 2 Lock_time: 0 Rows_sent: 0 Rows_examined: 0 SELECT * FROM ( SELECT products . *, categories.category_name AS category, ( SELECT COUNT( * ) FROM distros WHERE distros.product_id = products.product_id) AS distro_count, (SELECT COUNT(*) FROM downloads WHERE downloads.product_id = products.product_id AND WEEK(downloads.date) = WEEK(curdate())) AS true_downloads, (SELECT COUNT(*) FROM views WHERE views.product_id = products.product_id AND WEEK(views.date) = WEEK(curdate())) AS true_views FROM products INNER JOIN categories ON products.category_id = categories.category_id ORDER BY created_date DESC, true_views DESC ) AS count_table WHERE count_table.distro_count > 0 AND count_table.status = 'published' AND count_table.active = 1 LIMIT 0, 8 Heres the explain: +----+--------------------+------------+-------+---------------+-------------+---------+------------------------------------+------+----------------------------------------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+--------------------+------------+-------+---------------+-------------+---------+------------------------------------+------+----------------------------------------------+ | 1 | PRIMARY | <derived2> | ALL | NULL | NULL | NULL | NULL | 232 | Using where | | 2 | DERIVED | categories | index | PRIMARY | idx_name | 47 | NULL | 13 | Using index; Using temporary; Using filesort | | 2 | DERIVED | products | ref | category_id | category_id | 4 | digizald_db.categories.category_id | 9 | | | 5 | DEPENDENT SUBQUERY | views | ref | product_id | product_id | 4 | digizald_db.products.product_id | 46 | Using where | | 4 | DEPENDENT SUBQUERY | downloads | ref | product_id | product_id | 4 | digizald_db.products.product_id | 14 | Using where | | 3 | DEPENDENT SUBQUERY | distros | ref | product_id | product_id | 4 | digizald_db.products.product_id | 1 | Using index | +----+--------------------+------------+-------+---------------+-------------+---------+------------------------------------+------+----------------------------------------------+ 6 rows in set (0.04 sec) And the Tables: mysql> describe products; +---------------+--------------------------------------------------+------+-----+-------------------+----------------+ | Field | Type | Null | Key | Default | Extra | +---------------+--------------------------------------------------+------+-----+-------------------+----------------+ | product_id | int(10) unsigned | NO | PRI | NULL | auto_increment | | product_key | char(32) | NO | | NULL | | | title | varchar(150) | NO | | NULL | | | company | varchar(150) | NO | | NULL | | | user_id | int(10) unsigned | NO | MUL | NULL | | | description | text | NO | | NULL | | | video_code | text | NO | | NULL | | | category_id | int(10) unsigned | NO | MUL | NULL | | | price | decimal(10,2) | NO | | NULL | | | quantity | int(10) unsigned | NO | | NULL | | | downloads | int(10) unsigned | NO | | NULL | | | views | int(10) unsigned | NO | | NULL | | | status | enum('pending','published','rejected','removed') | NO | | NULL | | | active | tinyint(1) | NO | | NULL | | | deleted | tinyint(1) | NO | | NULL | | | created_date | datetime | NO | | NULL | | | modified_date | timestamp | NO | | CURRENT_TIMESTAMP | | | scrape_source | varchar(215) | YES | | NULL | | +---------------+--------------------------------------------------+------+-----+-------------------+----------------+ 18 rows in set (0.00 sec) mysql> describe categories -> ; +------------------+------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------------+------------------+------+-----+---------+----------------+ | category_id | int(10) unsigned | NO | PRI | NULL | auto_increment | | category_name | varchar(45) | NO | MUL | NULL | | | parent_id | int(10) unsigned | YES | MUL | NULL | | | category_type_id | int(10) unsigned | NO | | NULL | | +------------------+------------------+------+-----+---------+----------------+ 4 rows in set (0.00 sec) mysql> describe compatibilities -> ; +------------------+------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------------+------------------+------+-----+---------+----------------+ | compatibility_id | int(10) unsigned | NO | PRI | NULL | auto_increment | | name | varchar(45) | NO | | NULL | | | code_name | varchar(45) | NO | | NULL | | | description | varchar(128) | NO | | NULL | | | position | int(10) unsigned | NO | | NULL | | +------------------+------------------+------+-----+---------+----------------+ 5 rows in set (0.01 sec) mysql> describe distros -> ; +------------------+--------------------------------------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------------+--------------------------------------------------+------+-----+---------+----------------+ | id | int(10) unsigned | NO | PRI | NULL | auto_increment | | product_id | int(10) unsigned | NO | MUL | NULL | | | compatibility_id | int(10) unsigned | NO | MUL | NULL | | | user_id | int(10) unsigned | NO | | NULL | | | status | enum('pending','published','rejected','removed') | NO | | NULL | | | distro_type | enum('file','url') | NO | | NULL | | | version | varchar(150) | NO | | NULL | | | filename | varchar(50) | YES | | NULL | | | url | varchar(250) | YES | | NULL | | | virus | enum('READY','PASS','FAIL') | YES | | NULL | | | downloads | int(10) unsigned | NO | | 0 | | +------------------+--------------------------------------------------+------+-----+---------+----------------+ 11 rows in set (0.01 sec) mysql> describe downloads; +------------+------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------+------------------+------+-----+---------+----------------+ | id | int(10) unsigned | NO | PRI | NULL | auto_increment | | product_id | int(10) unsigned | NO | MUL | NULL | | | distro_id | int(10) unsigned | NO | MUL | NULL | | | user_id | int(10) unsigned | NO | MUL | NULL | | | ip_address | varchar(15) | NO | | NULL | | | date | datetime | NO | | NULL | | +------------+------------------+------+-----+---------+----------------+ 6 rows in set (0.01 sec) mysql> describe views -> ; +------------+------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------+------------------+------+-----+---------+----------------+ | id | int(10) unsigned | NO | PRI | NULL | auto_increment | | product_id | int(10) unsigned | NO | MUL | NULL | | | user_id | int(10) unsigned | NO | MUL | NULL | | | ip_address | varchar(15) | NO | | NULL | | | date | datetime | NO | | NULL | | +------------+------------------+------+-----+---------+----------------+ 5 rows in set (0.00 sec)

    Read the article

  • How can i clear a SQLite database each time i start my app

    - by AndroidUser99
    Hi, i want that each time i start my app my SQLite database get's cleaned for this, i need to make a method on my class MyDBAdapter.java code examples are welcome, i have no idea how to do it this is the dbadapter/helper i'm using: public class MyDbAdapter { private static final String TAG = "NotesDbAdapter"; private DatabaseHelper mDbHelper; private SQLiteDatabase mDb; private static final String DATABASE_NAME = "gpslocdb"; private static final String PERMISSION_TABLE_CREATE = "CREATE TABLE permission ( fk_email1 varchar, fk_email2 varchar, validated tinyint, hour1 time default '08:00:00', hour2 time default '20:00:00', date1 date, date2 date, weekend tinyint default '0', fk_type varchar, PRIMARY KEY (fk_email1,fk_email2))"; private static final String USER_TABLE_CREATE = "CREATE TABLE user ( email varchar, password varchar, fullName varchar, mobilePhone varchar, mobileOperatingSystem varchar, PRIMARY KEY (email))"; private static final int DATABASE_VERSION = 2; private final Context mCtx; private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(PERMISSION_TABLE_CREATE); db.execSQL(USER_TABLE_CREATE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS user"); db.execSQL("DROP TABLE IF EXISTS permission"); onCreate(db); } } /** * Constructor - takes the context to allow the database to be * opened/created * * @param ctx the Context within which to work */ public MyDbAdapter(Context ctx) { this.mCtx = ctx; } /** * Open the database. If it cannot be opened, try to create a new * instance of the database. If it cannot be created, throw an exception to * signal the failure * * @return this (self reference, allowing this to be chained in an * initialization call) * @throws SQLException if the database could be neither opened or created */ public MyDbAdapter open() throws SQLException { mDbHelper = new DatabaseHelper(mCtx); mDb = mDbHelper.getWritableDatabase(); return this; } public void close() { mDbHelper.close(); } public long createUser(String email, String password, String fullName, String mobilePhone, String mobileOperatingSystem) { ContentValues initialValues = new ContentValues(); initialValues.put("email",email); initialValues.put("password",password); initialValues.put("fullName",fullName); initialValues.put("mobilePhone",mobilePhone); initialValues.put("mobileOperatingSystem",mobileOperatingSystem); return mDb.insert("user", null, initialValues); } public Cursor fetchAllUsers() { return mDb.query("user", new String[] {"email", "password", "fullName", "mobilePhone", "mobileOperatingSystem"}, null, null, null, null, null); } public Cursor fetchUser(String email) throws SQLException { Cursor mCursor = mDb.query(true, "user", new String[] {"email", "password", "fullName", "mobilePhone", "mobileOperatingSystem"} , "email" + "=" + email, null, null, null, null, null); if (mCursor != null) { mCursor.moveToFirst(); } return mCursor; } public List<Friend> retrieveAllUsers() { List <Friend> friends=new ArrayList<Friend>(); Cursor result=fetchAllUsers(); if( result.moveToFirst() ){ do{ //note.getString(note.getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE))); friends.add(new Friend(result.getString(result.getColumnIndexOrThrow("email")), "","","","")); }while( result.moveToNext() ); } return friends; } }

    Read the article

  • Declaring data types in SQLite

    - by dan04
    I'm familiar with how type affinity works in SQLite: You can declare column types as anything you want, and all that matters is whether the type name contains "INT", "CHAR", "FLOA", etc. But is there a commonly-used convention on what type names to use? For example, if you have an integer column, is it better to distinguish between TINYINT, SMALLINT, MEDIUMINT, and BIGINT, or just declare everything as INTEGER? So far, I've been using the following: INTEGER REAL CHAR(n) -- for strings with a known fixed with VARCHAR(n) -- for strings with a known maximum width TEXT -- for all other strings BLOB BOOLEAN DATE -- string in "YYYY-MM-DD" format TIME -- string in "HH:MM:SS" format TIMESTAMP -- string in "YYYY-MM-DD HH:MM:SS" format (Note that the last three are contrary to the type affinity.)

    Read the article

  • What's the difference between !col and col=false in MySQL?

    - by Mask
    The two statements have totally different performance: mysql> explain select * from jobs where createIndexed=false; +----+-------------+-------+------+----------------------+----------------------+---------+-------+------+-------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+-------+------+----------------------+----------------------+---------+-------+------+-------+ | 1 | SIMPLE | jobs | ref | i_jobs_createIndexed | i_jobs_createIndexed | 1 | const | 1 | | +----+-------------+-------+------+----------------------+----------------------+---------+-------+------+-------+ 1 row in set (0.01 sec) mysql> explain select * from jobs where !createIndexed; +----+-------------+-------+------+---------------+------+---------+------+-------+-------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+-------+------+---------------+------+---------+------+-------+-------------+ | 1 | SIMPLE | jobs | ALL | NULL | NULL | NULL | NULL | 17996 | Using where | +----+-------------+-------+------+---------------+------+---------+------+-------+-------------+ Column definition and related index for aiding analysis: createIndexed tinyint(1) NOT NULL DEFAULT 0, create index i_jobs_createIndexed on jobs(createIndexed);

    Read the article

  • Is it possible to a db constraint in for this rule?

    - by Pure.Krome
    Hi folks, I wish to make sure that my data has a constraint the following check (constraint?) in place This table can only have one BorderColour per hub/category. (eg. #FFAABB) But it can have multiple nulls. (all the other rows are nulls, for this field) Table Schema ArticleId INT PRIMARY KEY NOT NULL HubId TINYINT NOT NULL CategoryId INT NOT NULL Title NVARCHAR(100) NOT NULL Content NVARCHAR(MAX) NOT NULL BorderColour VARCHAR(7) -- Can be nullable. I'm gussing I would have to make a check constraint? But i'm not sure how, etc. sample data. 1, 1, 1, 'test', 'blah...', '#FFAACC' 1, 1, 1, 'test2', 'sfsd', NULL 1, 1, 2, 'Test3', 'sdfsd dsf s', NULL 1, 1, 2, 'Test4', 'sfsdsss', '#AABBCC' now .. if i add the following line, i should get some sql error.... INSERT INTO tblArticle VALUES (1, 2, 'aaa', 'bbb', '#ABABAB') any ideas?

    Read the article

  • ALTER TABLE on dependant column

    - by Sharmi
    I am trying to alter column datatype of a primary key to tinyint from int.This column is a foreign key in other tables.So,I get the following error: Msg 5074, Level 16, State 1, Line 1 The object 'PK_User_tbl' is dependent on column 'appId'. Msg 5074, Level 16, State 1, Line 1 The object 'FK_Details_tbl_User_tbl' is dependent on column 'appId'. Msg 5074, Level 16, State 1, Line 1 The object 'FK_Log_tbl_User_tbl' is dependent on column 'appId'. Msg 4922, Level 16, State 9, Line 1 ALTER TABLE ALTER COLUMN appId failed because one or more objects access this column. Howw should i rectify this?

    Read the article

  • sql-server: how to select from dupilcate rows from table?

    - by RedsDevils
    Hi All, I have the following table. CREATE TABLE TEST(ID TINYINT NULL, COL1 CHAR(1)) INSERT INTO TEST(ID,COL1) VALUES (1,'A') INSERT INTO TEST(ID,COL1) VALUES (2,'B') INSERT INTO TEST(ID,COL1) VALUES (1,'A') INSERT INTO TEST(ID,COL1) VALUES (1,'B') INSERT INTO TEST(ID,COL1) VALUES (1,'B') INSERT INTO TEST(ID,COL1) VALUES (2,'B') I would like to select duplicate rows from that table. How Can I select? I try like the following: SELECT TEST.ID,TEST.COL1 FROM TEST WHERE TEST.ID IN (SELECT ID FROM TEST WHERE TEST.COL1 IN (SELECT COL1 FROM TEST WHERE TEST.ID IN (SELECT ID FROM TEST GROUP BY ID HAVING COUNT(*) > 1) GROUP BY COL1 HAVING COUNT(*) > 1) GROUP BY ID HAVING COUNT(*) > 1) Where's the Error? Can you modify that? Help me! Thanks in advance!

    Read the article

  • Help with complex sql query

    - by eugeneK
    To make story short, i'm building self-learning banner management system. Users will be able to insert these banners to their site when banners will be shown based on sales/impressions ratio. I have 4 tables Banners bannerID int bannerImage varchar.... SmartBanners smartBannerID int smartBannerArrayID int bannerID int impressionsCount int visibility tinyint (percents) SmartBannerArrays smartBannerArrayID int userID int Statistics bannerID int saleAmountPerDay decimal... Each night i need to generate new "visibility" for each SmartBanner based on whole SmartBannerArray that same user has. So i need to get sum of impressions and sales for each bannerID in SmartBannerArray. All comes to my mind is to use double cursor, one will loop thought SmartBannerArrays get needed values for sum of impressions and sales and then inner loop which will access each SmartBanner and change it's "visibility" percentage based on (sales/impressions)/(sumOfSales/sumOfImpressions)*100 Hope you get the picture... Is there any other way to design better tables or not to use double cursor to avoid server overload ?

    Read the article

  • What's wrong with this SQL UPDATE query?

    - by Tommo
    I wouldn't ask if i wasn't sure that i have 100% no idea why this isn't working, so, in PHP i'm simply trying to update a value in the MySQL database: The field im updating - Name: read - Type: tinyint - Length: 1 Here is the PHP code: do_SQL("UPDATE messages SET read=1 WHERE id='".$id."'"); The do_SQL function is working for everything else, so it's something wrong with this statement. I have tried putting 1 in '1' and it still didn't work.m The error is: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'read=1 WHERE id='1'' at line 1 Thanks for reading!

    Read the article

< Previous Page | 1 2 3 4 5 6  | Next Page >