Search Results

Search found 1805 results on 73 pages for 'varchar'.

Page 27/73 | < Previous Page | 23 24 25 26 27 28 29 30 31 32 33 34  | Next Page >

  • Ordering by a max or a min from another table

    - by Paul Tomblin
    I have a table that consists of a unique id, and a few other attributes. It holds "schedules". Then I have another table that holds a list of all the times each schedule has or will "fire". This isn't the exact schema, but it's close: create table schedule ( id varchar(40) primary key, attr1 int, attr2 varchar(20) ); create table schedule_times ( id varchar(40) foreign key schedule(id), fire_date date ); I want to query the schedule table, getting the attributes and the next and previous fire_dates, in Java, sometimes ordering on one of the attributes, but sometimes ordering on either previous fire_date or the next fire_date. Ordering by the attributes is easy, I just stick an "order by" into the string while I'm building my prepared statement. I'm not even sure how to go about selecting the last fire_date and the next one in a single query - I know that I can find the next fire_date for a given id by doing a SELECT min(fire_date) FROM schedule_times WHERE id = ? AND fire_date > sysdate; and the similar thing for previous fire_date using max() and fire_date < sysdate. I'm just drawing a blank on how to incorporate that into a single select from the schedule so I can get both next and previous fire_date in one shot, and also how to order by either of those attributes.

    Read the article

  • SQL 2008 Querying Soap XML

    - by Vince
    I have been trying to process this SOAP XML return using SQL but all I get is NULL or nothing at all. I have tried different ways and pasted them all below. Declare @xmlMsg xml; Set @xmlMsg = '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <soap:Body> <SendWarrantyEmailResponse xmlns="http://Web.Services.Warranty/"> <SendWarrantyEmailResult xmlns="http://Web.Services.SendWarrantyResult"> <WarrantyNumber>120405000000015</WarrantyNumber> <Result>Cannot Send Email to anonymous account!</Result> <HasError>true</HasError> <MsgUtcTime>2012-06-07T01:11:36.8665126Z</MsgUtcTime> </SendWarrantyEmailResult> </SendWarrantyEmailResponse> </soap:Body> </soap:Envelope>'; declare @table table (data xml); insert into @table values (@xmlMsg); select data from @table; WITH xmlnamespaces ('http://schemas.xmlsoap.org/soap/envelope/' as [soap], 'http://Web.Services.Warranty' as SendWarrantyEmailResponse, 'http://Web.Services.SendWarrantyResult' as SendWarrantyEmailResult) SELECT Data.value('(/soap:Envelope[1]/soap:Body[1]/SendWarrantyEmailResponse[1]/SendWarrantyEmailResult[1]/WarrantyNumber[1])[1]','VARCHAR(500)') AS WarrantyNumber FROM @Table ; ;with xmlnamespaces('http://schemas.xmlsoap.org/soap/envelope/' as [soap],'http://Web.Services.Warranty' as SendWarrantyEmailResponse,'http://Web.Services.SendWarrantyResult' as SendWarrantyEmailResult) --select @xmlMsg.value('(/soap:Envelope/soap:Body/SendWarrantyEmailResponse/SendWarrantyEmailResult/WarrantyNumber)[0]', 'nvarchar(max)') --select T.N.value('.', 'nvarchar(max)') from @xmlMsg.nodes('/soap:Envelope/soap:Body/SendWarrantyEmailResponse/SendWarrantyEmailResult') as T(N) select @xmlMsg.value('(/soap:Envelope/soap:Body/SendWarrantyEmailResponse/SendWarrantyEmailResult/HasError)[1]','bit') as test ;with xmlnamespaces('http://schemas.xmlsoap.org/soap/envelope/' as [soap],'http://Web.Services.Warranty' as [SendWarrantyEmailResponse],'http://Web.Services.SendWarrantyResult' as [SendWarrantyEmailResult]) SELECT SendWarrantyEmailResult.value('WarrantyNumber[1]','varchar(max)') AS WarrantyNumber, SendWarrantyEmailResult.value('Result[1]','varchar(max)') AS Result, SendWarrantyEmailResult.value('HasError[1]','bit') AS HasError, SendWarrantyEmailResult.value('MsgUtcTime[1]','datetime') AS MsgUtcTime FROM @xmlMsg.nodes('/soap:Envelope/soap:Body/SendWarrantyEmailResponse/SendWarrantyEmailResult') SendWarrantyEmailResults(SendWarrantyEmailResult)

    Read the article

  • Mysql return value as 0 in the fetch result.

    - by Karthik
    I have this two tables, -- -- Table structure for table `t1` -- CREATE TABLE `t1` ( `pid` varchar(20) collate latin1_general_ci NOT NULL, `pname` varchar(20) collate latin1_general_ci NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci; -- -- Dumping data for table `t1` -- INSERT INTO `t1` VALUES ('p1', 'pro1'); INSERT INTO `t1` VALUES ('p2', 'pro2'); -- -------------------------------------------------------- -- -- Table structure for table `t2` -- CREATE TABLE `t2` ( `pid` varchar(20) collate latin1_general_ci NOT NULL, `year` int(6) NOT NULL, `price` int(3) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci; -- -- Dumping data for table `t2` -- INSERT INTO `t2` VALUES ('p1', 2009, 50); INSERT INTO `t2` VALUES ('p1', 2010, 60); INSERT INTO `t2` VALUES ('p3', 2007, 200); INSERT INTO `t2` VALUES ('p4', 2008, 501); my query is, SELECT * FROM `t1` LEFT JOIN `t2` ON t1.pid = t2.pid Getting the result, pid pname pid year price p1 pro1 p1 2009 50 p1 pro1 p1 2010 60 p2 pro2 NULL NULL NULL My question is, i want to get the price value is 0 instead of NULL. How can i write the query to getting the price value is 0. Thanks in advance for help.

    Read the article

  • Find out which row caused the error

    - by Felipe Fiali
    I have a big fat query that's written dynamically to integrate some data. Basically what it does is query some tables, join some other ones, treat some data, and then insert it into a final table. The problem is that there's too much data, and we can't really trust the sources, because there could be some errored or inconsistent data. For example, I've spent almost an hour looking for an error while developing using a customer's database because somewhere in the middle of my big fat query there was an error converting some varchar to datetime. It turned out to be that they had some sales dating '2009-02-29', an out-of-range date. And yes, I know. Why was that stored as varchar? Well, the source database has 3 columns for dates, 'Month', 'Day' and 'Year'. I have no idea why it's like that, but still, it is. But how the hell would I treat that, if the source is not trustable? I can't HANDLE exceptions, I really need that it comes up to another level with the original message, but I wanted to provide some more info, so that the user could at least try to solve it before calling us. So I thought about displaying to the user the row number, or some ID that would at least give him some idea of what record he'd have to correct. That's also a hard job because there will be times when the integration will run up to 80000 records. And in an 80000 records integration, a single dummy error message: 'The conversion of a varchar data type to a datetime data type resulted in an out-of-range datetime value' means nothing at all. So any idea would be appreciated. Oh I'm using SQL Server 2005 with Service Pack 3.

    Read the article

  • Creating a [materialised]view from generic data in Oracle/Mysql

    - by Andrew White
    I have a generic datamodel with 3 tables CREATE TABLE Properties ( propertyId int(11) NOT NULL AUTO_INCREMENT, name varchar(80) NOT NULL ) CREATE TABLE Customers ( customerId int(11) NOT NULL AUTO_INCREMENT, customerName varchar(80) NOT NULL ) CREATE TABLE PropertyValues ( propertyId int(11) NOT NULL, customerId int(11) NOT NULL, value varchar(80) NOT NULL ) INSERT INTO Properties VALUES (1, 'Age'); INSERT INTO Properties VALUES (2, 'Weight'); INSERT INTO Customers VALUES (1, 'Bob'); INSERT INTO Customers VALUES (2, 'Tom'); INSERT INTO PropertyValues VALUES (1, 1, '34'); INSERT INTO PropertyValues VALUES (2, 1, '80KG'); INSERT INTO PropertyValues VALUES (1, 2, '24'); INSERT INTO PropertyValues VALUES (2, 2, '53KG'); What I would like to do is create a view that has as columns all the ROWS in Properties and has as rows the entries in Customers. The column values are populated from PropertyValues. e.g. customerId Age Weight 1 34 80KG 2 24 53KG I'm thinking I need a stored procedure to do this and perhaps a materialised view (the entries in the table "Properties" change rarely). Any tips?

    Read the article

  • mysql whats wrong with this query?

    - by Hailwood
    I'm trying to write a query that selects from four tables campaignSentParent csp campaignSentEmail cse campaignSentFax csf campaignSentSms css Each of the cse, csf, and css tables are linked to the csp table by csp.id = (cse/csf/css).parentId The csp table has a column called campaignId, What I want to do is end up with rows that look like: | id | dateSent | emailsSent | faxsSent | smssSent | | 1 | 2011-02-04 | 139 | 129 | 140 | But instead I end up with a row that looks like: | 1 | 2011-02-03 | 2510340 | 2510340 | 2510340 | Here is the query I am trying SELECT csp.id id, csp.dateSent dateSent, COUNT(cse.parentId) emailsSent, COUNT(csf.parentId) faxsSent, COUNT(css.parentId) smsSent FROM campaignSentParent csp, campaignSentEmail cse, campaignSentFax csf, campaignSentSms css WHERE csp.campaignId = 1 AND csf.parentId = csp.id AND cse.parentId = csp.id AND css.parentId = csp.id; Adding GROUP BY did not help, so I am posting the create statements. csp CREATE TABLE `campaignsentparent` ( `id` int(11) NOT NULL AUTO_INCREMENT, `campaignId` int(11) NOT NULL, `dateSent` datetime NOT NULL, `account` int(11) NOT NULL, `status` varchar(15) NOT NULL DEFAULT 'Creating', PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=latin1 cse/csf (same structure, different names) CREATE TABLE `campaignsentemail` ( `id` int(11) NOT NULL AUTO_INCREMENT, `parentId` int(11) NOT NULL, `contactId` int(11) NOT NULL, `content` text, `subject` text, `status` varchar(15) DEFAULT 'Pending', PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=140 DEFAULT CHARSET=latin1 css CREATE TABLE `campaignsentsms` ( `id` int(11) NOT NULL AUTO_INCREMENT, `parentId` int(11) NOT NULL, `contactId` int(11) NOT NULL, `content` text, `status` varchar(15) DEFAULT 'Pending', PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=141 DEFAULT CHARSET=latin1

    Read the article

  • How Can i Create This Complicated Query ?

    - by mTuran
    Hi, I have 3 tables: projects, skills and project_skills. In projects table i hold project's general data. Second table skills i hold skill id and skill name also i have projects_skills table which is hold project's skill relationships. Here is scheme of tables: CREATE TABLE IF NOT EXISTS `project_skills` ( `project_id` int(11) NOT NULL, `skill_id` int(11) NOT NULL, KEY `project_id` (`project_id`), KEY `skill_id` (`skill_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_turkish_ci; CREATE TABLE IF NOT EXISTS `projects` ( `id` int(11) NOT NULL AUTO_INCREMENT, `employer_id` int(11) NOT NULL, `project_title` varchar(100) COLLATE utf8_turkish_ci NOT NULL, `project_description` text COLLATE utf8_turkish_ci NOT NULL, `project_budget` int(11) NOT NULL, `project_allowedtime` int(11) NOT NULL, `project_deadline` datetime NOT NULL, `total_bids` int(11) NOT NULL, `average_bid` int(11) NOT NULL, `created` datetime NOT NULL, `active` tinyint(1) NOT NULL, PRIMARY KEY (`id`), KEY `created` (`created`), KEY `employer_id` (`employer_id`), KEY `active` (`active`), FULLTEXT KEY `project_title` (`project_title`,`project_description`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_turkish_ci AUTO_INCREMENT=3 ; CREATE TABLE IF NOT EXISTS `skills` ( `id` int(11) NOT NULL AUTO_INCREMENT, `category` int(11) NOT NULL, `name` varchar(100) COLLATE utf8_turkish_ci NOT NULL, `seo_name` varchar(100) COLLATE utf8_turkish_ci NOT NULL, `total_projects` int(11) NOT NULL, PRIMARY KEY (`id`), KEY `seo_name` (`seo_name`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_turkish_ci AUTO_INCREMENT=224 ; I want to select projects with related skill names. I think i have to use JOIN but i don't know how can i do. Thanks

    Read the article

  • SQL Server getdate() to a string like "2009-12-20"

    - by Adam Kane
    In Microsoft SQL Server 2005 and .NET 2.0, I want to convert the current date to a string of this format: "YYYY-MM-DD". For example, December 12th 2009 would become "2009-12-20". How do I do this in SQL. The context of this SQL statement in the table definiton. In other words, this is the default value. So when a new record is created the default value of the current date is stored as a string in the above format. I'm trying: SELECT CONVERT(VARCHAR(10), GETDATE(), 102) AS [YYYY.MM.DD] But SQL server keeps converting that to: ('SELECT CONVERT(VARCHAR(10), GETDATE(), 102) AS [YYYY.MM.DD]') so the result is just: 'SELECT CONVERT(VARCHAR(10), GETDATE(), 102) AS [YYYY.MM.DD]' Here's a screen shot of what the Visual Studio server explorer, table, table definition, properties shows: These wrapper bits are being adding automatically and converting it all to literal string: (N' ') Here's the reason I'm trying to use something other than the basic DATETIME I was using previously: This is the error I get when hooking everything to an ASP.NET GridView and try to do an update via the grid view: Server Error in '/' Application. The version of SQL Server in use does not support datatype 'date'. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.ArgumentException: The version of SQL Server in use does not support datatype 'date'. Source Error: An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. Stack Trace: [ArgumentException: The version of SQL Server in use does not support datatype 'date'.] Note: I've added a related question to try to get around the SQL Server in use does not support datatype 'date' error so that I can use a DATETIME as recommended.

    Read the article

  • Using an ORM with a database that has no defined relationships?

    - by Ahmad
    Consider a database(MSSQL 2005) that consists of 100+ tables which have primary keys defined to a certain degree. There are 'relationships' between tables, however these are not enforced with foreign key constraints. Consider the following simplified example of typical types of tables I am dealing with. The are clear relations between the User and City and Province tables. However, they key issues is the inconsistent data types in the tables and naming conventions. User: UserRowId [int] PK Name [varchar(50)] CityId [smallint] ProvinceRowId [bigint] City: CityRowId [bigint] PK CityDescription [varchar(100)] Province: ProvinceId [int] PK ProvinceDesc [varchar(50)] I am considering a rewrite of the application (in ASP.net MVC) that uses this data source as is similar in design to MVC storefront. However I am going through a proof of concept phase and this is one of the stumbling blocks I have come across. What are my options in terms of ORM choice that can be easily used and why? Should I even be considering an ORM? (The reason I ask this is that most explanations and tutorials all work with relatively cleanly designed existing databases, or newly created ones when compared to mine. I am thus having a very hard time trying to find a way forward with this problem) There is a huge amount of existing SQL queries, would a datamappper(eg IBatis.net) be more suitable since we could easily modify them to work and reuse the investment already made? I have found this question on SO which indicates to me that an ORM can be used - however I get the impression that this a question of mapping? Note: at the moment, the object model is not clearly defined as it was non-existent. The existing system pretty much did almost everything in SQL or consisted of overly complicated, and numerous queries to complete fucntionality. I am pretty much a noob and have zero experience around ORMs and MVC - so this an awesome learning curve I am on.

    Read the article

  • mysql query help, take total sum from a table, and based on discount value on another table calcula

    - by vegatron
    hi I have a table called invoices: CREATE TABLE IF NOT EXISTS `si_invoices` ( `id` int(10) NOT NULL AUTO_INCREMENT, `biller_id` int(10) NOT NULL DEFAULT '0', `customer_id` int(10) NOT NULL DEFAULT '0', `type_id` int(10) NOT NULL DEFAULT '0', `inv_tax_id` int(10) NOT NULL, `date` date NOT NULL DEFAULT '0000-00-00', `unreg_customer` tinyint(1) NOT NULL DEFAULT '0', `discount` decimal(10,2) NOT NULL DEFAULT '0.00', `discount_type` tinyint(1) NOT NULL DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=20 ; each invoice has items that are stored in invoice_items table : CREATE TABLE IF NOT EXISTS `si_invoice_items` ( `id` int(10) NOT NULL AUTO_INCREMENT, `invoice_id` int(10) NOT NULL DEFAULT '0', `quantity` int(10) unsigned NOT NULL DEFAULT '0', `product_id` int(10) DEFAULT '0', `warehouse_id` int(10) NOT NULL, `unit_price` decimal(25,2) DEFAULT '0.00', `total` decimal(25,2) DEFAULT '0.00', `description` text, PRIMARY KEY (`id`), KEY `invoice_id` (`invoice_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=56 ; and tax table CREATE TABLE IF NOT EXISTS `si_tax` ( `tax_id` int(11) NOT NULL AUTO_INCREMENT, `tax_description` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, `tax_percentage` decimal(25,6) DEFAULT '0.000000', `type` varchar(1) COLLATE utf8_unicode_ci DEFAULT NULL, `tax_enabled` varchar(1) COLLATE utf8_unicode_ci NOT NULL DEFAULT '1', PRIMARY KEY (`tax_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=5 ; here is what I want to do step 1: get the sum_total of the invoice Items for a speciefic invoice step 2: calculate the discount, in the invoice table I have a discount_type field : if its equal to 0 , then there will be no discount if its equal to 1 , the discount value will be stored in the discount field if its equal to 2 , the discount is a percentage of sum_total step 3: calculate the taxes based on inv_tax_id based on the tax id , I will look in the tax table , get the tax_percentage and multiply it by the (sum_total - discount) in short here is the equation $gross_total = $sum_total - $disount + taxes

    Read the article

  • SQL SERVER FOR XML SYNTAX

    - by Raj73
    How can I get an output as follows using FOR XML / sql query. I am not sure how I can get the Column Values as Elements instead of the tables' column Names. I am using sql server 2005 I HAVE TABLE SCEMA AS FOLLOWS CREATE TABLE PARENT ( PID INT, PNAME VARCHAR(20) ) CREATE TABLE CHILD ( PID INT, CID INT, CNAME VARCHAR(20) ) CREATE TABLE CHILDVALUE ( CID INT, CVALUE VARCHAR(20) ) INSERT INTO PARENT VALUES (1, 'SALES1') INSERT INTO PARENT VALUES (2, 'SALES2') INSERT INTO CHILD VALUES (1, 1, 'FOR01') INSERT INTO CHILD VALUES (1, 2, 'FOR02') INSERT INTO CHILD VALUES (2, 3, 'FOR03') INSERT INTO CHILD VALUES (2, 4, 'FOR04') INSERT INTO CHILDVALUE VALUES (1, '250000') INSERT INTO CHILDVALUE VALUES (2, '400000') INSERT INTO CHILDVALUE VALUES (3, '500000') INSERT INTO CHILDVALUE VALUES (4, '800000') The Output I am looking for is as follows <SALE1> <FOR01>250000</FOR01> <FOR02>400000</FOR02> </SALE1> <SALE2> <FOR03>500000</FOR03> <FOR04>800000</FOR04> </SALE2>

    Read the article

  • How do I access Dictionary items?

    - by salvationishere
    I am developing a C# VS2008 / SQL Server website app and am new to the Dictionary class. Can you please advise on best method of accomplishing this? Here is a code snippet: SqlConnection conn2 = new SqlConnection(connString); SqlCommand cmd = conn2.CreateCommand(); cmd.CommandText = "dbo.AppendDataCT"; cmd.CommandType = CommandType.StoredProcedure; cmd.Connection = conn2; SqlParameter p1, p2, p3; foreach (string s in dt.Rows[1].ItemArray) { DataRow dr = dt.Rows[1]; // second row p1 = cmd.Parameters.AddWithValue((string)dic[0], (string)dr[0]); p1.SqlDbType = SqlDbType.VarChar; p2 = cmd.Parameters.AddWithValue((string)dic[1], (string)dr[1]); p2.SqlDbType = SqlDbType.VarChar; p3 = cmd.Parameters.AddWithValue((string)dic[2], (string)dr[2]); p3.SqlDbType = SqlDbType.VarChar; } but this is giving me compiler error: The best overloaded method match for 'System.Collections.Generic.Dictionary<string,string>.this[string]' has some invalid arguments I just want to access each value from "dic" and load into these SQL parameters. How do I do this? Do I have to enter the key? The keys are named "col1", "col2", etc., so not the most user-friendly. Any other tips? Thanks!

    Read the article

  • .NET 3.5 DataGridView Wont Save To Database

    - by Jimbo
    I have created a test Winforms application in Visual Studio 2008 (SP1) to see just how "RAD" C# and .NET 3.5 can be. So far I have mixed emotions. Added a service-based database to my application (MyDB.mdf) and added two tables - Contact (id [identity], name [varchar] and number [varchar] columns) and Group (id [identity] and name [varchar] columns) Added a DataSource, selected "Database" as the source, used the default connection string as the connection (which points to my database) and selected "All Tables" to be included in the data source and saved as MyDBDataSet Expanded the data source showing my two tables, selected the "Group" table and chose to display it as a DataGridView (from the dropdown option on the right of each entity) and dragged it onto Form1, thus creating a groupBindingNavigator, groupBindingSource, groupTableAdapter, tableAdapterManager, myDBDataset and groupDataGridView Press F5 to test the application, enter the name "Test" under the DataGridView's "name" column and click "Save" on the navigator which has autogenerated code to save the data that looks like this: private void groupBindingNavigatorSaveItem_Click(object sender, EventArgs e) { this.Validate(); this.groupBindingSource.EndEdit(); this.tableAdapterManager.UpdateAll(this.myDBDataSet); } Stop the application and have a look at the database data, you will see no data saved there in the "Group" table. I dont know why and cant find out how to fix it! Googled for about 30 minutes with no luck. The code is auto-generated with the controls, so you'd think that it would work too :)

    Read the article

  • How can get unique values from data table using dql?

    - by piemesons
    I am having a table in which there is a column in which various values are stored.i want to retrieve unique values from that table using dql. Doctrine_Query::create() ->select('rec.school') ->from('Records rec') ->where("rec.city='$city' ") ->execute(); Now i want only unique values. Can anybody tell me how to do that... Edit Table Structure: CREATE TABLE IF NOT EXISTS `records` ( `id` int(11) NOT NULL AUTO_INCREMENT, `state` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `city` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `school` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=16334 ; This is the Query I am using: Doctrine_Query::create() ->select('DISTINCT rec.city') ->from('Records rec') ->where("rec.state = '$state'") // ->getSql(); ->execute(); Generting Sql for this gives me: SELECT DISTINCT r.id AS r__id, r.city AS r__city FROM records r WHERE r.state = 'AR' Now check the sql generated:::: DISTINCT is on 'id' column where as i want Distinct on city column. Anybody know how to fix this. EDIT2 Id is unique cause its an auto incremental value.Ya i have some real duplicates in city column like: Delhi and Delhi. Right.. Now when i am trying to fetch data from it, I am getting Delhi two times. How can i make query like this: select DISTINCT rec.city where state="xyz"; Cause this will give me the proper output. EDIT3: Anybody who can tell me how to figure out this query..???

    Read the article

  • How to fix this simple SQL query?

    - by morpheous
    I have a database with three tables: user_table country_table city_table I want to write ANSI SQL which will allow me to fetch all the user data (i.e. user details including the name of the country of the last school and the name of the city they live in now). The problem I am having is that I have to use a self join, and I am getting slightly confused. The schema is shown below: CREATE TABLE user_table (id int, first_name varchar(16), last_school_country_id int, city_id int); CREATE TABLE country_table (id int, name varchar(32)); CREATE TABLE city_table (id int, country_id int, name varchar(32)); This is the query I have come up with so far, but the results are wrong, and sometimes, the db engine (mySQL), asks me if I want to show all [HUGE NUMBER HERE] results - which makes me suspect that I am unintentionally creating a cartesian product somewhere. Can someone explain what is wrong with this SQL statement, and what I need to do to fix it? SELECT usr.id AS id, usr.first_name, ctry1.name as loc_country_name, ctry2.name as school_country_name, city.name as loc_city_name FROM user_table usr, country_table ctry1, country_table ctry2, city_table city WHERE usr.last_school_country_id=ctry2.id AND usr.city_id=city.id AND city.country_id=ctry1.id AND ctry1.id=ctry2.id;

    Read the article

  • SQL Server: Can you help me with this query?

    - by rlb.usa
    I want to run a diagnostic report on our MS SQL 2008 database server. I am looping through all of the databases, and then for each database, I want to look at each table. But, when I go to look at each table (with tbl_cursor), it always picks up the tables in the database 'master'. I think it's because of my tbl_cursor selection : SELECT table_name FROM information_schema.tables WHERE table_type = 'base table' How do I fix this? Here's the entire code: SET NOCOUNT ON DECLARE @table_count INT DECLARE @db_cursor VARCHAR(100) DECLARE database_cursor CURSOR FOR SELECT name FROM sys.databases where name<>N'master' OPEN database_cursor FETCH NEXT FROM database_cursor INTO @db_cursor WHILE @@Fetch_status = 0 BEGIN PRINT @db_cursor SET @table_count = 0 DECLARE @table_cursor VARCHAR(100) DECLARE tbl_cursor CURSOR FOR SELECT table_name FROM information_schema.tables WHERE table_type = 'base table' OPEN tbl_cursor FETCH NEXT FROM tbl_cursor INTO @table_cursor WHILE @@Fetch_status = 0 BEGIN DECLARE @table_cmd NVARCHAR(255) SET @table_cmd = N'IF NOT EXISTS( SELECT TOP(1) * FROM ' + @table_cursor + ') PRINT N'' Table ''''' + @table_cursor + ''''' is empty'' ' --PRINT @table_cmd --debug EXEC sp_executesql @table_cmd SET @table_count = @table_count + 1 FETCH NEXT FROM tbl_cursor INTO @table_cursor END CLOSE tbl_cursor DEALLOCATE tbl_cursor PRINT @db_cursor + N' Total Tables : ' + CAST( @table_count as varchar(2) ) PRINT N'' -- print another blank line SET @table_count = 0 FETCH NEXT FROM database_cursor INTO @db_cursor END CLOSE database_cursor DEALLOCATE database_cursor SET NOCOUNT OFF

    Read the article

  • Suggestion on Database structure for relational data

    - by miccet
    Hi there. I've been wrestling with this problem for quite a while now and the automatic mails with 'Slow Query' warnings are still popping in. Basically, I have Blogs with a corresponding table as well as a table that keeps track of how many times each Blog has been viewed. This last table has a huge amount of records since this page is relatively high traffic and it logs every hit as an individual row. I have tried with indexes on the fields that are included in the WHERE clause, but it doesn't seem to help. I have also tried to clean the table each week by removing old ( 1.weeks) records. SO, I'm asking you guys, how would you solve this? The query that I know is causing the slowness is generated by Rails and looks like this: SELECT count(*) AS count_all FROM blog_views WHERE (created_at >= '2010-01-01 00:00:01' AND blog_id = 1); The tables have the following structures: CREATE TABLE IF NOT EXISTS 'blogs' ( 'id' int(11) NOT NULL auto_increment, 'name' varchar(255) default NULL, 'perma_name' varchar(255) default NULL, 'author_id' int(11) default NULL, 'created_at' datetime default NULL, 'updated_at' datetime default NULL, 'blog_picture_id' int(11) default NULL, 'blog_picture2_id' int(11) default NULL, 'page_id' int(11) default NULL, 'blog_picture3_id' int(11) default NULL, 'active' tinyint(1) default '1', PRIMARY KEY ('id'), KEY 'index_blogs_on_author_id' ('author_id') ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; And CREATE TABLE IF NOT EXISTS 'blog_views' ( 'id' int(11) NOT NULL auto_increment, 'blog_id' int(11) default NULL, 'ip' varchar(255) default NULL, 'created_at' datetime default NULL, 'updated_at' datetime default NULL, PRIMARY KEY ('id'), KEY 'index_blog_views_on_blog_id' ('blog_id'), KEY 'created_at' ('created_at') ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

    Read the article

  • MySQL error code:1329 in function

    - by Sharad Sharma
    DELIMITER // CREATE DEFINER=`root`@`localhost` FUNCTION `formatMovieNames`(lID int) RETURNS varchar(1000) CHARSET latin1 BEGIN DECLARE output varchar(1000); DECLARE done INT DEFAULT 0; declare a varchar(200); declare cur1 cursor for select fileName from swlp4_movie where movieID in (select movieID from lesson_movie_map where lessonID = lID order by lm_map_id); DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; open cur1; read_loop: loop fetch cur1 into a; if done = 1 then leave read_loop; end if; set output = concat(output, 'movie:[',a,']<br/>'); set output = substr(output, 0, length(@output)-5); end loop; close cur1; RETURN output; END// I have create this function and when I run it I do not get any output (select fileName from swlp4_movie where movieID in (select movieID from lesson_movie_map where lessonID = 24 order by lm_map_id)); brings correct result I am trying to get result as movie:['movieName']< br / movie:['movieName1'] and so on (had to change br tag, cause it was adding a line break) cant't figure out what I am doing wrong

    Read the article

  • How to use Transaction in Entity FrameWork?

    - by programmerist
    How to use Transaction in Entity FrameWork? i read some links on Stackoverflow : http://stackoverflow.com/questions/815586/entity-framework-using-transactions-or-savechangesfalse-and-acceptallchanges BUT; i have 3 table so i have 3 entities: CREATE TABLE Personel (PersonelID integer PRIMARY KEY identity not null, Ad varchar(30), Soyad varchar(30), Meslek varchar(100), DogumTarihi datetime, DogumYeri nvarchar(100), PirimToplami float); Go create TABLE Prim (PrimID integer PRIMARY KEY identity not null, PersonelID integer Foreign KEY references Personel(PersonelID), SatisTutari int, Prim float, SatisTarihi Datetime); Go CREATE TABLE Finans (ID integer PRIMARY KEY identity not null, Tutar float); Personel, Prim,Finans my tables. if you look Prim table you can see Prim value float value if i write a textbox not float value my transaction must run. using (TestEntities testCtx = new TestEntities()) { using (TransactionScope scope = new TransactionScope()) { // do someyihng... testCtx.Personel.SaveChanges(); // do someyihng... testCtx.Prim.SaveChanges(); // do someyihng... testCtx.Finans.SaveChanges(); scope .Complete(); success = true; } } How can i do that?

    Read the article

  • Delete all previous records and insert new ones

    - by carlos
    When updating an employee with id = 1 for example, what is the best way to delete all previous records in the table certificate for this employee_id and insert the new ones?. create table EMPLOYEE ( id INT NOT NULL auto_increment, first_name VARCHAR(20) default NULL, last_name VARCHAR(20) default NULL, salary INT default NULL, PRIMARY KEY (id) ); create table CERTIFICATE ( id INT NOT NULL auto_increment, certificate_name VARCHAR(30) default NULL, employee_id INT default NULL, PRIMARY KEY (id) ); Hibernate mapping <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="Employee" table="EMPLOYEE"> <id name="id" type="int" column="id"> <generator class="sequence"> <param name="sequence">employee_seq</param> </generator> </id> <set name="certificates" lazy="false" cascade="all"> <key column="employee_id" not-null="true"/> <one-to-many class="Certificate"/> </set> <property name="firstName" column="first_name"/> <property name="lastName" column="last_name"/> <property name="salary" column="salary"/> </class> <class name="Certificate" table="CERTIFICATE"> <id name="id" type="int" column="id"> <param name="sequence">certificate_seq</param> </id> <property name="employee_id" column="employee_id" insert="false" update="false"/> <property name="name" column="certificate_name"/> </class> </hibernate-mapping>

    Read the article

  • How do I iterate through hierarchical data in a Sql Server 2005 stored proc?

    - by AlexChilcott
    Hi, I have a SqlServer2005 table "Group" similar to the following: Id (PK, int) Name (varchar(50)) ParentId (int) where ParentId refers to another Id in the Group table. This is used to model hierarchical groups such as: Group 1 (id = 1, parentid = null) +--Group 2 (id = 2, parentid = 1) +--Group 3 (id = 3, parentid = 1) +--Group 4 (id = 4, parentid = 3) Group 5 (id = 5, parentid = null) +--Group 6 (id = 6, parentid = 5) You get the picture I have another table, let's call it "Data" for the sake of simplification, which looks something like: Id (PK, int) Key (varchar) Value (varchar) GroupId (FK, int) Now, I am trying to write a stored proc which can get me the "Data" for a given group. For example, if I query for group 1, it returns me the Key-Value-Pairs from Data where groupId = 1. If I query for group 2, it returns the KVPs for groupId = 1, then unioned with those which have groupId = 2 (and duplicated keys are replaced). Ideally, the sproc would also fail gracefully if there is a cycle (ie if group 1's parent is group 2 and group 2's parent is group 1) Has anyone had experience in writing such a sproc, or know how this might be accomplished? Thanks guys, much appreciated, Alex

    Read the article

  • MySQL Casting in C#

    - by user798080
    Okay, so I'm attempting to print out the contents of a table in a comma-separated file. using (OdbcCommand com = new OdbcCommand("SELECT * FROM pie_data WHERE Pie_ID = ?", con)) { com.Parameters.AddWithValue("", Request.Form["pie_id"]); com.ExecuteNonQuery(); using (OdbcDataReader reader = com.ExecuteReader()) { string finalstring = ""; while (reader.Read()) { finalstring = reader.GetString(9) + ","; for (int i = 0; i <= 8; i = i + 1) { finalstring = finalstring + reader.GetString(i) + ","; } } } Response.Write(finalstring); noredirect = 1; } My table layout is: CREATE TABLE `rent_data` ( `Pies` INT(10) UNSIGNED NOT NULL, `Name` VARCHAR(85) NOT NULL, `Email` VARCHAR(85) NOT NULL, `Pie_Rent` DATE NOT NULL, `Rent_To` DATE NOT NULL, `Returned_Date` DATE NULL DEFAULT NULL, `Place` VARCHAR(100) NOT NULL, `Purpose` MEDIUMTEXT NOT NULL, `Comments` MEDIUMTEXT NULL, `Pie_ID` SMALLINT(5) UNSIGNED ZEROFILL NOT NULL, INDEX `Pie_ID` (`Equipment_ID`) ) The error I'm getting is this: Exception Details: System.InvalidCastException: Unable to cast object of type 'System.Int64' to type 'System.String'. On the line: finalstring = finalstring + reader.GetString(i) + ",";

    Read the article

  • MySQL: optimization of table (indexing, foreign key) with no primary keys

    - by Haradzieniec
    Each member has 0 or more orders. Each order contains at least 1 item. memberid - varchar, not integer - that's OK (please do not mention that's not very good, I can't change it). So, thera 3 tables: members, orders and order_items. Orders and order_items are below: CREATE TABLE `orders` ( `orderid` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, `memberid` VARCHAR( 20 ), `Time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP , `info` VARCHAR( 3200 ) NULL , PRIMARY KEY (orderid) , FOREIGN KEY (memberid) REFERENCES members(memberid) ) ENGINE = InnoDB; CREATE TABLE `order_items` ( `orderid` INT(11) UNSIGNED NOT NULL, `item_number_in_cart` tinyint(1) NOT NULL , --- 5 items in cart= 5 rows `price` DECIMAL (6,2) NOT NULL, FOREIGN KEY (orderid) REFERENCES orders(orderid) ) ENGINE = InnoDB; So, order_items table looks like: orderid - item_number_in_cart - price: ... 1000456 - 1 - 24.99 1000456 - 2 - 39.99 1000456 - 3 - 4.99 1000456 - 4 - 17.97 1000457 - 1 - 20.00 1000458 - 1 - 99.99 1000459 - 1 - 2.99 1000459 - 2 - 69.99 1000460 - 1 - 4.99 ... As you see, order_items table has no primary keys (and I think there is no sense to create an auto_increment id for this table, because once we want to extract data, we always extract it as WHERE orderid='1000456' order by item_number_in_card asc - the whole block, id woudn't be helpful in queries). Once data is inserted into order_items, it's not UPDATEd, just SELECTed. The questions are: I think it's a good idea to put index on item_number_in_cart. Could anybody please confirm that? Is there anything else I have to do with order_items to increase the performance, or that looks pretty good? I could miss something because I'm a newbie. Thank you in advance.

    Read the article

  • SQL Server 2005: Internal Query Processor Error:

    - by Geetha
    I am trying to execute this following procedure in SQL Server 2005. I was able to execute this in my development server and when i tried to use this in the Live Server I am getting an Error "Internal Query Processor Error: The query processor could not produce a query plan. For more information, contact Customer Support Services". am using the same Database and the same format. when we searched in the web it shows some fixes to be used in sql server 2005 to avoid this error but my DBA has confirmed that all the patches are updated in our server. can anyone give me some clue on this. Query: create Procedure [dbo].[sample_Select] @ID as varchar(40) as Declare @Execstring as varchar(1000) set @Execstring = ' Declare @MID as varchar(40) Set @MID = '''+@ID+''' select * from ( select t1.field1, t1.field2 AS field2 , t1.field3 AS field3 , L.field1 AS field1 , L. field2 AS field2 from table1 AS t1 INNER JOIN MasterTable AS L ON L. field1 = t1. field2 where t1. field2 LIKE @MID ) as DataTable PIVOT ( Count(field2) FOR field3 IN (' Select @Execstring=@Execstring+ L.field2 +',' FROM MasterTable AS L inner join table1 AS t1 ON t1.field1= L.field2 Where t1.field2 LIKE @ID set @Execstring = stuff(@Execstring, len(@Execstring), 1, '') set @Execstring =@Execstring +')) as pivotTable' exec (@Execstring)

    Read the article

  • Create 2nd tables and add data

    - by Tyler Matema
    I have this task from school, and I am confuse and lost on how I got to do this. So basically I have to create 2 tables to the database but I have to created from php. I have created the first table, but not the second one for some reason. And then, I have to populate first and second tables with 10 and 20 sample records respectively, populate, does it mean like adding more fake users? if so is it like the code shown below? *I got error on the populating second part as well Thank you so much for the help. <?php $host = "host"; $user = "me"; $pswd = "password"; $dbnm = "db"; $conn = @mysqli_connect($host, $user, $pswd, $dbnm); if (!$conn) die ("<p>Couldn't connect to the server!<p>"); $selectData = @mysqli_select_db ($conn, $dbnm); if(!$selectData) { die ("<p>Database Not Selected</p>"); } //1st table $sql = "CREATE TABLE IF NOT EXISTS `friends` ( `friend_id` INT NOT NULL auto_increment, `friend_email` VARCHAR(20) NOT NULL, `password` VARCHAR(20) NOT NULL, `profile_name` VARCHAR(30) NOT NULL, `date_started` DATE NOT NULL, `num_of_friends` INT unsigned, PRIMARY KEY (`friend_id`) )"; //2nd table $sqlMyfriends = "CREATE TABLE `myfriends` ( `friend_id1` INT NOT NULL, `friend_id2` INT NOT NULL, )"; $query_result1 = @mysqli_query($conn, $sql); $query_result2 = @mysqli_query($conn, $sqlMyfriends); //populating 1st table $sqlSt3="INSERT INTO friends (friend_id, friend_email, password, profile_name, date_started, num_of_friends) VALUES('NULL','[email protected]','123','abc','2012-10-25', 5)"; $queryResult3 = @mysqli_query($dbConnect,$sqlSt3) //populating 2nd table $sqlSt13="INSERT INTO myfriends VALUES(1,2)"; $queryResult13=@mysqli_query($dbConnect,$sqlSt13); mysqli_close($conn); ?>

    Read the article

< Previous Page | 23 24 25 26 27 28 29 30 31 32 33 34  | Next Page >