Search Results

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

Page 13/73 | < Previous Page | 9 10 11 12 13 14 15 16 17 18 19 20  | Next Page >

  • oracle clob insertion problem in spring

    - by haluk
    Hi, I want to insert CLOB value into my Oracle database and here is the what I could do. I got this exception while inserting operation "ORA-01461: can bind a LONG value only for insert into a LONG column". Would someone able to tell me what should I do? Thanks. List<Object> listObjects = dao.selectAll("TABLE NAME", new XRowMapper()); String queryX = "INSERT INTO X (A,B,C,D,E,F) VALUES ?,?,?,?,?,XMLTYPE(?))"; OracleLobHandler lobHandler = new OracleLobHandler(); for(Object myObject : listObjects) { dao.create(queryX, new Object[]{ ((X)myObject).getA(), ((X)myObject).getB(), new SqlLobValue (((X)myObject).getC(), lobHandler), ((X)myObject).getD(), ((X)myObject).getE(), ((X)myObject).getF() }, new int[] {Types.VARCHAR,Types.VARCHAR,Types.CLOB,Types.VARCHAR,Types.VARCHAR,Types.VARCHAR}); }

    Read the article

  • need thoughts on my interview question - .net, c#

    - by uno
    One of the questions I was asked was that I have a database table with following columns pid - unique identifier orderid - varchar(20) documentid - int documentpath - varchar(250) currentLocation - varchar(250) newlocation - varchar(250) status - varchar(15) I have to write a c# app to move the files from currentlocation to newlocation and update status column as either 'SUCCESS' or 'FAILURE'. This was my answer Create a List of all the records using linq Create a command object which would be perform moving files using foreach, invoke a delegate to move the files - use endinvoke to capture any exception and update the db accordingly I was told that command pattern and delegate did not fit the bill here - i was aksed to think and implement a more favorable GoF pattern. Not sure what they were looking for - In this day and age, do candidates keep a lot of info on head as one always has google to find any answer and come up with solution.

    Read the article

  • Store data for songs MySQL DB

    - by Johan
    I'm storing a huge set of songs in a MySQL database. This is what I store in the 'songs' table: CREATE TABLE `songs` ( `song_id` int(10) unsigned NOT NULL auto_increment, `song_artist` varchar(255) NOT NULL, `song_track` varchar(255) NOT NULL, `song_mix` varchar(255) NOT NULL, `song_title` text NOT NULL, `song_hash` varchar(40) NOT NULL, `song_addtime` int(10) unsigned NOT NULL, `song_source` text NOT NULL, `song_file` varchar(255) NOT NULL, PRIMARY KEY (`song_id`) ) ENGINE=MyISAM AUTO_INCREMENT=1857 DEFAULT CHARSET=latin1 Now I'd like to keep track of how many plays each song has, and other song-specific data that relates to the song. I don't want to keep adding fields to the 'songs' table for this. How can I store song related data a more efficient way? What's the best practice here?

    Read the article

  • MySQL ignores the NOT NULL constraint

    - by Marga Keuvelaar
    I have created a table with NOT NULL constraints on some columns in MySQL. Then in PHP I wrote a script to insert data, with an insert query. When I omit one of the NOT NULL columns in this insert statement I would expect an error message from MySQL, and I would expect my script to fail. Instead, MySQL inserts empty strings in the NOT NULL fields. In other omitted fields the data is NULL, which is fine. Could someone tell me what I did wrong here? I'm using this table: CREATE TABLE IF NOT EXISTS tblCustomers ( cust_id int(11) NOT NULL AUTO_INCREMENT, custname varchar(50) NOT NULL, company varchar(50), phone varchar(50), email varchar(50) NOT NULL, country varchar(50) NOT NULL, ... date_added timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (cust_id) ) ; And this insert statement: $sql = "INSERT INTO tblCustomers (custname,company) VALUES ('".$customerName."','".$_POST["CustomerCompany"]."')"; $res = mysqli_query($mysqli, $sql);

    Read the article

  • php, mySQL - how to create a table?

    - by user296516
    Hi guys, I have written a code that should check weather there is a table called imei.$addimei and, if not, create it... $userdatabase = mysqli_connect('localhost', 'root', 'marina', 'imei'); ... $result = mysqli_query($userdatabase, "SELECT * FROM imei".$addimei."" ); if ( !$result ) { echo('creating table...'); /// if no such table, make one! mysql_query ( $userdatabase, 'CREATE TABLE imei'.$addimei.'( ID int NOT NULL AUTO_INCREMENT, PRIMARY KEY(ID), EVENT varchar(15), TIME varchar(25), FLD1 varchar(35), FLD2 varchar(35), IP varchar(25), )' ); } Yet the CREATE TABLE somehow doesn't seem to work. Warning: mysql_query() expects parameter 1 to be string, object given in C:\xampp\xampp\htdocs\mobi\mainmenu.php on line 564 Any idea's what wrong? Thanks!

    Read the article

  • mysql query - syntax error - cannot find out why

    - by Phil Jackson
    Hi all, im taring my hair out over this one. A query is throwing an error: 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 'FROM, SUBJECT, DATE, READ, MAIL ) VALUES ( 'EJackson', 'dfdf', '1270974101', 'fa' at line 1 I printed out the query to see what could be the problem: INSERT INTO db.tablename ( FROM, SUBJECT, DATE, READ, MAIL ) VALUES ( 'EJackson', 'dfdf', '1270974299', 'false', 'dfdsfdsfd' ) and finaly the structure consists of: CREATE TABLE db.tablename ( `ID` int(12) NOT NULL auto_increment, `FROM` varchar(255) NOT NULL, `SUBJECT` varchar(255) NOT NULL, `DATE` varchar(255) NOT NULL, `READ` varchar(255) NOT NULL, `MAIL` varchar(255) NOT NULL, PRIMARY KEY (`ID`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; I cant find anything wrong. Any Help would be much appreciated. ( db.tablename is a replacement for the actual tablename )

    Read the article

  • mysql ignores not null constraint?

    - by Marga Keuvelaar
    I have created a table with NOT NULL constraints on some columns in MySQL. Then in PHP I wrote a script to insert data, with an insert query. When I omit one of the NOT NULL columns in this insert statement I would expect an error message from MySQL, and I would expect my script to fail. Instead, MySQL inserts empty strings in the NOT NULL fields. In other omitted fields the data is NULL, which is fine. Could someone tell me what I did wrong here? I'm using this table: CREATE TABLE IF NOT EXISTS tblCustomers ( cust_id int(11) NOT NULL AUTO_INCREMENT, custname varchar(50) NOT NULL, company varchar(50), phone varchar(50), email varchar(50) NOT NULL, country varchar(50) NOT NULL, ... date_added timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (cust_id) ) ; And this insert statement: $sql = "INSERT INTO tblCustomers (custname,company) VALUES ('".$customerName."','".$_POST["CustomerCompany"]."')"; $res = mysqli_query($mysqli, $sql);

    Read the article

  • Why does concatenating strings in the argument of EXEC sometimes cause a syntax error in T-SQL?

    - by Tim Goodman
    In MS SQL Server Management Studio 2005, running this code EXEC('SELECT * FROM employees WHERE employeeID = ' + CAST(3 AS VARCHAR)) gives this error: Incorrect syntax near 'CAST' However, if I do this, it works: DECLARE @temp VARCHAR(4000) SET @temp = 'SELECT * FROM employees WHERE employeeID = ' + CAST(3 AS VARCHAR) EXEC(@temp) I found an explanation here: http://stackoverflow.com/questions/1044831/t-sql-cannot-pass-concatenated-string-as-argument-to-stored-procedure According to the accepted answer, EXEC can take a local variable or a value as its argument, but not an expression. However, if that's the case, why does this work: DECLARE @temp VARCHAR(4000) SET @temp = CAST(3 AS VARCHAR) EXEC('SELECT * FROM employees WHERE employeeID = ' + @temp) 'SELECT * FROM employees WHERE employeeID = ' + @temp sure looks like an expression to me, but the code executes with no errors.

    Read the article

  • sql jdbc getgeneratedkeys with mysql returns column "id" not found

    - by iamrohitbanga
    I want to retrieve the most recently updated value in the table using an insert query. these are the datatypes in my sql table. int(11) // primary key auto increment, not being assigned by sqlQuery varchar(30) timestamp // has a default value. but i am explicit assigning it using CURRENT_TIMESTAMP varchar(300) varchar(300) varchar(300) int(11) varchar(300) // java code statement.executeUpdate(sqlQuery, Statement.RETURN_GENERATED_KEYS); ResultSet rs = statement.getGeneratedKeys(); System.out.println("here: " + rs.getMetaData().getColumnCount()); System.out.println("here1: " + rs.getMetaData().getColumnName(1)); // none of the following 3 works System.out.println("id: " + rs.getInt(1)); System.out.println("id: " + rs.getInt("GENERATED_KEY")); System.out.println("id: " + rs.getInt("id")); for a bit of background see this

    Read the article

  • Linq to SQl Stored Procedure Problem( it can't figure out the return type)

    - by chobo2
    Hi I have this SP USE [Test] GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE PROCEDURE [dbo].[UsersInsert](@UpdatedProdData XML) AS INSERT INTO dbo.UserTable(UserId,UserName,LicenseId,Password,PasswordSalt,Email,IsApproved,IsLockedOut,CreateDate, LastLoginDate,LastLockOutDate,FailedPasswordAttempts,RoleId) SELECT @UpdatedProdData.value('(/ArrayOfUsers/Users/UserId)[1]', 'uniqueidentifier'), @UpdatedProdData.value('(/ArrayOfUsers/Users/UserName)[1]', 'varchar(20)'), @UpdatedProdData.value('(/ArrayOfUsers/Users/LicenseId)[1]', 'varchar(50)'), @UpdatedProdData.value('(/ArrayOfUsers/Users/Password)[1]', 'varchar(128)'), @UpdatedProdData.value('(/ArrayOfUsers/Users/PasswordSalt)[1]', 'varchar(128)'), @UpdatedProdData.value('(/ArrayOfUsers/Users/Email)[1]', 'varchar(50)'), @UpdatedProdData.value('(/ArrayOfUsers/Users/IsApproved)[1]', 'bit'), @UpdatedProdData.value('(/ArrayOfUsers/Users/IsLockedOut)[1]', 'bit'), @UpdatedProdData.value('(/ArrayOfUsers/Users/CreateDate)[1]', 'datetime'), @UpdatedProdData.value('(/ArrayOfUsers/Users/LastLoginDate)[1]', 'datetime'), @UpdatedProdData.value('(/ArrayOfUsers/Users/LastLockOutDate)[1]', 'datetime'), @UpdatedProdData.value('(/ArrayOfUsers/Users/FailedPasswordAttempts)[1]', 'int'), @UpdatedProdData.value('(/ArrayOfUsers/Users/RoleId)[1]', 'int') Now this SP creates just fine. It's when I go to VS2010 and try to drag this SP in my method panel of my linq to sql file in design view. It tells me that it can't figure out the return type. I try to go to the properties but it does not have "none" as a choice and I can't type it in. It should be "none" so how do I set it to "none"?

    Read the article

  • How to strore Java Date to Mysql datetime...?

    - by user275843
    can any body tell me how can i store Java Date to Mysql datetime...? when i am trying to do so...only date is stored and time remain 00:00:00 in mysql date stores like this... 2009-09-22 00:00:00 i want not only date but also time...like 2009-09-22 08:08:11 please help me.... EDIT---- i am using JPA(Hibernate) with spring mydomain classes uses java.util.Date but i have created tables using handwritten queries... this is my create statement CREATE TABLE ContactUs (id BIGINT auto_increment, userName VARCHAR(30), email VARCHAR(50), subject VARCHAR(100), message VARCHAR(1024), messageType VARCHAR(15), contactUsTime datetime, primary key(id))TYPE=InnoDB;

    Read the article

  • SQLite: 2 Problems by working with table

    - by TianDong
    Hallo all, I have a SQliteDatabase object db, i want to create a table in db with the following code db.execSQL("CREATE TABLE IF NOT EXISTS "+ TABLE2_NAME + " (exer_nr INTEGER PRIMARY KEY ,exerText varchar(250),answerA varchar(250),answerB varchar(250),answerC varchar(250),answerD varchar(250))"); An Error occur. Why? Is this too large? How can i fix it? Another problem: I want to insert a row into the table, whose "exerText" column contains the following code as part of it's content. main( ) { int m=12, n=34; printf("%d%d", m+ +,+ +n); printf("%d%d\n",n+ +,+ +m); } An Error occur because of the "" and '' symbols in the code. How can i fix this problem ? Thanks a lot

    Read the article

  • how to get key value of array with curl (php)

    - by Vierri
    Hello I want to make use of an API but it print alot of info and i don't know how i can get a few key values of the array. <?php $query = "SELECT * FROM kvk WHERE adres='Wit-geellaan 158'"; $host = "http://api.openkvk.nl/php/"; $url = $host ."/". rawurlencode($query); $curl = curl_init(); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_HEADER, 0); curl_exec($curl); curl_close($curl); ?> Is my php script and it shows array(array("RESULT"=>array("TYPES"=>array("int","bigint","varchar","varchar","varchar","varchar","varchar","int","int","smallint","smallint","int"),"HEADER"=>array("id","kvk","bedrijfsnaam","adres","postcode","plaats","type","kvks","sub","bedrijfsnaam_size","adres_size","verhuisd"),"ROWS"=>array(array("1303095","271242250000","Schoonmaakbedrijf Regio","Wit-geellaan 158","2718CK","Zoetermeer","Hoofdvestiging","27124225","0","23","16","0"))))) Thanks in advance Greetings, Vierri

    Read the article

  • how to use constants in SQL CREATE TABLE?

    - by kchiu
    Hi, I have 3 SQL tables, defined as follows: CREATE TABLE organs( abbreviation VARCHAR(16), -- ... other stuff ); CREATE TABLE blocks( abbreviation VARCHAR(16), -- ... other stuff ); CREATE TABLE slides( title VARCHAR(16), -- ... other stuff ); The 3 fields above all use VARCHAR(16) because they're related and have the same length restriction. Is there a (preferably portable) way to put '16' into a constant / variable and reference that instead in CREATE TABLE? eg. something like this would be nice: CREATE TABLE slides( title VARCHAR(MAX_TITLE_LENGTH), -- ... other stuff ); I'm using PostgreSQL 8.4. thanks a lot, and Happy New Year! cheers.

    Read the article

  • SQL SERVER – Update Statistics are Sampled By Default

    - by pinaldave
    After reading my earlier post SQL SERVER – Create Primary Key with Specific Name when Creating Table on Statistics, I have received another question by a blog reader. The question is as follows: Question: Are the statistics sampled by default? Answer: Yes. The sampling rate can be specified by the user and it can be anywhere between a very low value to 100%. Let us do a small experiment to verify if the auto update on statistics is left on. Also, let’s examine a very large table that is created and statistics by default- whether the statistics are sampled or not. USE [AdventureWorks] GO -- Create Table CREATE TABLE [dbo].[StatsTest]( [ID] [int] IDENTITY(1,1) NOT NULL, [FirstName] [varchar](100) NULL, [LastName] [varchar](100) NULL, [City] [varchar](100) NULL, CONSTRAINT [PK_StatsTest] PRIMARY KEY CLUSTERED ([ID] ASC) ) ON [PRIMARY] GO -- Insert 1 Million Rows INSERT INTO [dbo].[StatsTest] (FirstName,LastName,City) SELECT TOP 1000000 'Bob', CASE WHEN ROW_NUMBER() OVER (ORDER BY a.name)%2 = 1 THEN 'Smith' ELSE 'Brown' END, CASE WHEN ROW_NUMBER() OVER (ORDER BY a.name)%10 = 1 THEN 'New York' WHEN ROW_NUMBER() OVER (ORDER BY a.name)%10 = 5 THEN 'San Marino' WHEN ROW_NUMBER() OVER (ORDER BY a.name)%10 = 3 THEN 'Los Angeles' ELSE 'Houston' END FROM sys.all_objects a CROSS JOIN sys.all_objects b GO -- Update the statistics UPDATE STATISTICS [dbo].[StatsTest] GO -- Shows the statistics DBCC SHOW_STATISTICS ("StatsTest"PK_StatsTest) GO -- Clean up DROP TABLE [dbo].[StatsTest] GO Now let us observe the result of the DBCC SHOW_STATISTICS. The result shows that Resultset is for sure sampling for a large dataset. The percentage of sampling is based on data distribution as well as the kind of data in the table. Before dropping the table, let us check first the size of the table. The size of the table is 35 MB. Now, let us run the above code with lesser number of the rows. USE [AdventureWorks] GO -- Create Table CREATE TABLE [dbo].[StatsTest]( [ID] [int] IDENTITY(1,1) NOT NULL, [FirstName] [varchar](100) NULL, [LastName] [varchar](100) NULL, [City] [varchar](100) NULL, CONSTRAINT [PK_StatsTest] PRIMARY KEY CLUSTERED ([ID] ASC) ) ON [PRIMARY] GO -- Insert 1 Hundred Thousand Rows INSERT INTO [dbo].[StatsTest] (FirstName,LastName,City) SELECT TOP 100000 'Bob', CASE WHEN ROW_NUMBER() OVER (ORDER BY a.name)%2 = 1 THEN 'Smith' ELSE 'Brown' END, CASE WHEN ROW_NUMBER() OVER (ORDER BY a.name)%10 = 1 THEN 'New York' WHEN ROW_NUMBER() OVER (ORDER BY a.name)%10 = 5 THEN 'San Marino' WHEN ROW_NUMBER() OVER (ORDER BY a.name)%10 = 3 THEN 'Los Angeles' ELSE 'Houston' END FROM sys.all_objects a CROSS JOIN sys.all_objects b GO -- Update the statistics UPDATE STATISTICS [dbo].[StatsTest] GO -- Shows the statistics DBCC SHOW_STATISTICS ("StatsTest"PK_StatsTest) GO -- Clean up DROP TABLE [dbo].[StatsTest] GO You can see that Rows Sampled is just the same as Rows of the table. In this case, the sample rate is 100%. Before dropping the table, let us also check the size of the table. The size of the table is less than 4 MB. Let us compare the Result set just for a valid reference. Test 1: Total Rows: 1000000, Rows Sampled: 255420, Size of the Table: 35.516 MB Test 2: Total Rows: 100000, Rows Sampled: 100000, Size of the Table: 3.555 MB The reason behind the sample in the Test1 is that the data space is larger than 8 MB, and therefore it uses more than 1024 data pages. If the data space is smaller than 8 MB and uses less than 1024 data pages, then the sampling does not happen. Sampling aids in reducing excessive data scan; however, sometimes it reduces the accuracy of the data as well. Please note that this is just a sample test and there is no way it can be claimed as a benchmark test. The result can be dissimilar on different machines. There are lots of other information can be included when talking about this subject. I will write detail post covering all the subject very soon. Reference: Pinal Dave (http://blog.SQLAuthority.com) Filed under: Pinal Dave, SQL, SQL Authority, SQL Index, SQL Optimization, SQL Performance, SQL Query, SQL Scripts, SQL Server, SQL Tips and Tricks, T SQL, Technology Tagged: SQL Statistics

    Read the article

  • SQL SERVER – Finding Different ColumnName From Almost Identitical Tables

    - by pinaldave
    I have mentioned earlier on this blog that I love social media – Facebook and Twitter. I receive so many interesting questions that sometimes I wonder how come I never faced them in my real life scenario. Well, let us see one of the similar situation. Here is one of the questions which I received on my social media handle. “Pinal, I have a large database. I did not develop this database but I have inherited this database. In our database we have many tables but all the tables are in pairs. We have one archive table and one current table. Now here is interesting situation. For a while due to some reason our organization has stopped paying attention to archive data. We did not archive anything for a while. If this was not enough we  even changed the schema of current table but did not change the corresponding archive table. This is now becoming a huge huge problem. We know for sure that in current table we have added few column but we do not know which ones. Is there any way we can figure out what are the new column added in the current table and does not exist in the archive tables? We cannot use any third party tool. Would you please guide us?” Well here is the interesting example of how we can use sys.column catalogue views and get the details of the newly added column. I have previously written about EXCEPT over here which is very similar to MINUS of Oracle. In following example we are going to create two tables. One of the tables has extra column. In our resultset we will get the name of the extra column as we are comparing the catalogue view of the column name. USE AdventureWorks2012 GO CREATE TABLE ArchiveTable (ID INT, Col1 VARCHAR(10), Col2 VARCHAR(100), Col3 VARCHAR(100)); CREATE TABLE CurrentTable (ID INT, Col1 VARCHAR(10), Col2 VARCHAR(100), Col3 VARCHAR(100), ExtraCol INT); GO -- Columns in ArchiveTable but not in CurrentTable SELECT name ColumnName FROM sys.columns WHERE OBJECT_NAME(OBJECT_ID) = 'ArchiveTable' EXCEPT SELECT name ColumnName FROM sys.columns WHERE OBJECT_NAME(OBJECT_ID) = 'CurrentTable' GO -- Columns in CurrentTable but not in ArchiveTable SELECT name ColumnName FROM sys.columns WHERE OBJECT_NAME(OBJECT_ID) = 'CurrentTable' EXCEPT SELECT name ColumnName FROM sys.columns WHERE OBJECT_NAME(OBJECT_ID) = 'ArchiveTable' GO DROP TABLE ArchiveTable; DROP TABLE CurrentTable; GO The above query will return us following result. I hope this solves the problems. It is not the most elegant solution ever possible but it works. Here is the puzzle back to you – what native T-SQL solution would you have provided in this situation? Reference: Pinal Dave (http://blog.sqlauthority.com) Filed under: PostADay, SQL, SQL Authority, SQL Query, SQL Server, SQL System Table, SQL Tips and Tricks, T SQL, Technology

    Read the article

  • Advantage Database Server: slow stored procedure performance.

    - by ie
    I have a question about a performance of stored procedures in the ADS. I created a simple database with the following structure: CREATE TABLE MainTable ( Id INTEGER PRIMARY KEY, Name VARCHAR(50), Value INTEGER ); CREATE UNIQUE INDEX MainTableName_UIX ON MainTable ( Name ); CREATE TABLE SubTable ( Id INTEGER PRIMARY KEY, MainId INTEGER, Name VARCHAR(50), Value INTEGER ); CREATE INDEX SubTableMainId_UIX ON SubTable ( MainId ); CREATE UNIQUE INDEX SubTableName_UIX ON SubTable ( Name ); CREATE PROCEDURE CreateItems ( MainName VARCHAR ( 20 ), SubName VARCHAR ( 20 ), MainValue INTEGER, SubValue INTEGER, MainId INTEGER OUTPUT, SubId INTEGER OUTPUT ) BEGIN DECLARE @MainName VARCHAR ( 20 ); DECLARE @SubName VARCHAR ( 20 ); DECLARE @MainValue INTEGER; DECLARE @SubValue INTEGER; DECLARE @MainId INTEGER; DECLARE @SubId INTEGER; @MainName = (SELECT MainName FROM __input); @SubName = (SELECT SubName FROM __input); @MainValue = (SELECT MainValue FROM __input); @SubValue = (SELECT SubValue FROM __input); @MainId = (SELECT MAX(Id)+1 FROM MainTable); @SubId = (SELECT MAX(Id)+1 FROM SubTable ); INSERT INTO MainTable (Id, Name, Value) VALUES (@MainId, @MainName, @MainValue); INSERT INTO SubTable (Id, Name, MainId, Value) VALUES (@SubId, @SubName, @MainId, @SubValue); INSERT INTO __output SELECT @MainId, @SubId FROM system.iota; END; CREATE PROCEDURE UpdateItems ( MainName VARCHAR ( 20 ), MainValue INTEGER, SubValue INTEGER ) BEGIN DECLARE @MainName VARCHAR ( 20 ); DECLARE @MainValue INTEGER; DECLARE @SubValue INTEGER; DECLARE @MainId INTEGER; @MainName = (SELECT MainName FROM __input); @MainValue = (SELECT MainValue FROM __input); @SubValue = (SELECT SubValue FROM __input); @MainId = (SELECT TOP 1 Id FROM MainTable WHERE Name = @MainName); UPDATE MainTable SET Value = @MainValue WHERE Id = @MainId; UPDATE SubTable SET Value = @SubValue WHERE MainId = @MainId; END; CREATE PROCEDURE SelectItems ( MainName VARCHAR ( 20 ), CalculatedValue INTEGER OUTPUT ) BEGIN DECLARE @MainName VARCHAR ( 20 ); @MainName = (SELECT MainName FROM __input); INSERT INTO __output SELECT m.Value * s.Value FROM MainTable m INNER JOIN SubTable s ON m.Id = s.MainId WHERE m.Name = @MainName; END; CREATE PROCEDURE DeleteItems ( MainName VARCHAR ( 20 ) ) BEGIN DECLARE @MainName VARCHAR ( 20 ); DECLARE @MainId INTEGER; @MainName = (SELECT MainName FROM __input); @MainId = (SELECT TOP 1 Id FROM MainTable WHERE Name = @MainName); DELETE FROM SubTable WHERE MainId = @MainId; DELETE FROM MainTable WHERE Id = @MainId; END; Actually, the problem I had - even so light stored procedures work very-very slow (about 50-150 ms) relatively to plain queries (0-5ms). To test the performance, I created a simple test (in F# using ADS ADO.NET provider): open System; open System.Data; open System.Diagnostics; open Advantage.Data.Provider; let mainName = "main name #"; let subName = "sub name #"; // INSERT let cmdTextScriptInsert = " DECLARE @MainId INTEGER; DECLARE @SubId INTEGER; @MainId = (SELECT MAX(Id)+1 FROM MainTable); @SubId = (SELECT MAX(Id)+1 FROM SubTable ); INSERT INTO MainTable (Id, Name, Value) VALUES (@MainId, :MainName, :MainValue); INSERT INTO SubTable (Id, Name, MainId, Value) VALUES (@SubId, :SubName, @MainId, :SubValue); SELECT @MainId, @SubId FROM system.iota;"; let cmdTextProcedureInsert = "CreateItems"; // UPDATE let cmdTextScriptUpdate = " DECLARE @MainId INTEGER; @MainId = (SELECT TOP 1 Id FROM MainTable WHERE Name = :MainName); UPDATE MainTable SET Value = :MainValue WHERE Id = @MainId; UPDATE SubTable SET Value = :SubValue WHERE MainId = @MainId;"; let cmdTextProcedureUpdate = "UpdateItems"; // SELECT let cmdTextScriptSelect = " SELECT m.Value * s.Value FROM MainTable m INNER JOIN SubTable s ON m.Id = s.MainId WHERE m.Name = :MainName;"; let cmdTextProcedureSelect = "SelectItems"; // DELETE let cmdTextScriptDelete = " DECLARE @MainId INTEGER; @MainId = (SELECT TOP 1 Id FROM MainTable WHERE Name = :MainName); DELETE FROM SubTable WHERE MainId = @MainId; DELETE FROM MainTable WHERE Id = @MainId;"; let cmdTextProcedureDelete = "DeleteItems"; let cnnStr = @"data source=D:\DB\test.add; ServerType=local; user id=adssys; password=***;"; let cnn = new AdsConnection(cnnStr); try cnn.Open(); let cmd = cnn.CreateCommand(); let parametrize ix prms = cmd.Parameters.Clear(); let addParam = function | "MainName" -> cmd.Parameters.Add(":MainName" , mainName + ix.ToString()) |> ignore; | "SubName" -> cmd.Parameters.Add(":SubName" , subName + ix.ToString() ) |> ignore; | "MainValue" -> cmd.Parameters.Add(":MainValue", ix * 3 ) |> ignore; | "SubValue" -> cmd.Parameters.Add(":SubValue" , ix * 7 ) |> ignore; | _ -> () prms |> List.iter addParam; let runTest testData = let (cmdType, cmdName, cmdText, cmdParams) = testData; let toPrefix cmdType cmdName = let prefix = match cmdType with | CommandType.StoredProcedure -> "Procedure-" | CommandType.Text -> "Script -" | _ -> "Unknown -" in prefix + cmdName; let stopWatch = new Stopwatch(); let runStep ix prms = parametrize ix prms; stopWatch.Start(); cmd.ExecuteNonQuery() |> ignore; stopWatch.Stop(); cmd.CommandText <- cmdText; cmd.CommandType <- cmdType; let startId = 1500; let count = 10; for id in startId .. startId+count do runStep id cmdParams; let elapsed = stopWatch.Elapsed; Console.WriteLine("Test '{0}' - total: {1}; per call: {2}ms", toPrefix cmdType cmdName, elapsed, Convert.ToInt32(elapsed.TotalMilliseconds)/count); let lst = [ (CommandType.Text, "Insert", cmdTextScriptInsert, ["MainName"; "SubName"; "MainValue"; "SubValue"]); (CommandType.Text, "Update", cmdTextScriptUpdate, ["MainName"; "MainValue"; "SubValue"]); (CommandType.Text, "Select", cmdTextScriptSelect, ["MainName"]); (CommandType.Text, "Delete", cmdTextScriptDelete, ["MainName"]) (CommandType.StoredProcedure, "Insert", cmdTextProcedureInsert, ["MainName"; "SubName"; "MainValue"; "SubValue"]); (CommandType.StoredProcedure, "Update", cmdTextProcedureUpdate, ["MainName"; "MainValue"; "SubValue"]); (CommandType.StoredProcedure, "Select", cmdTextProcedureSelect, ["MainName"]); (CommandType.StoredProcedure, "Delete", cmdTextProcedureDelete, ["MainName"])]; lst |> List.iter runTest; finally cnn.Close(); And I'm getting the following results: Test 'Script -Insert' - total: 00:00:00.0292841; per call: 2ms Test 'Script -Update' - total: 00:00:00.0056296; per call: 0ms Test 'Script -Select' - total: 00:00:00.0051738; per call: 0ms Test 'Script -Delete' - total: 00:00:00.0059258; per call: 0ms Test 'Procedure-Insert' - total: 00:00:01.2567146; per call: 125ms Test 'Procedure-Update' - total: 00:00:00.7442440; per call: 74ms Test 'Procedure-Select' - total: 00:00:00.5120446; per call: 51ms Test 'Procedure-Delete' - total: 00:00:01.0619165; per call: 106ms The situation with the remote server is much better, but still a great gap between plaqin queries and stored procedures: Test 'Script -Insert' - total: 00:00:00.0709299; per call: 7ms Test 'Script -Update' - total: 00:00:00.0161777; per call: 1ms Test 'Script -Select' - total: 00:00:00.0258113; per call: 2ms Test 'Script -Delete' - total: 00:00:00.0166242; per call: 1ms Test 'Procedure-Insert' - total: 00:00:00.5116138; per call: 51ms Test 'Procedure-Update' - total: 00:00:00.3802251; per call: 38ms Test 'Procedure-Select' - total: 00:00:00.1241245; per call: 12ms Test 'Procedure-Delete' - total: 00:00:00.4336334; per call: 43ms Is it any chance to improve the SP performance? Please advice. ADO.NET driver version - 9.10.2.9 Server version - 9.10.0.9 (ANSI - GERMAN, OEM - GERMAN) Thanks!

    Read the article

  • Troubleshooting PG Function

    - by Grasper
    I have this function: CREATE OR REPLACE FUNCTION CREATE_AIRSPACE_AVAILABILITY_RECORD (cur_user VARCHAR, start_time VARCHAR, start_date VARCHAR, end_time VARCHAR, end_date VARCHAR, airspace_name VARCHAR) RETURNS VOID AS ' DECLARE c_user ALIAS for $1; BEGIN IF start_time IS NULL OR start_date IS NULL OR end_time IS NULL OR end_date IS NULL THEN INSERT INTO c_user.AIRSPACE_AVAILABILITY (ASP_AIRSPACE_NM, ASA_TIME_ID, ASA_START_DT, ASA_END_DT) SELECT airspace_name, 1, ABP.ABP_START_DT, ABP.ABP_STOP_DT FROM ABP WHERE EXISTS (SELECT ASP.ASP_AIRSPACE_NM FROM AIRSPACE ASP WHERE ASP.ASP_AIRSPACE_NM = airspace_name); ELSIF start_time IS NOT NULL AND start_date IS NOT NULL AND end_time IS NOT NULL AND end_date IS NOT NULL THEN INSERT INTO c_user.AIRSPACE_AVAILABILITY (ASP_AIRSPACE_NM, ASA_TIME_ID, ASA_START_DT, ASA_END_DT) SELECT airspace_name, 1, TO_DATE(start_date||start_time,''YYMMDDHH24MI''), TO_DATE(end_date||end_time,''YYMMDDHH24MI'') FROM DUAL WHERE EXISTS (SELECT ASP.ASP_AIRSPACE_NM FROM c_user.AIRSPACE ASP WHERE ASP.ASP_AIRSPACE_NM = airspace_name); END IF; END ; ' LANGUAGE plpgsql; I try calling it like so: select * from CREATE_AIRSPACE_AVAILABILITY_RECORD('user1','','','','',''); and I get this error: ERROR: schema "c_user" does not exist SQL state: 3F000 Context: SQL statement "INSERT INTO c_user.AIRSPACE_AVAILABILITY (ASP_AIRSPACE_NM, ASA_TIME_ID, ASA_START_DT, ASA_END_DT) SELECT $1 , 1, TO_DATE( $2 || $3 ,'YYMMDDHH24MI'), TO_DATE( $4 || $5 ,'YYMMDDHH24MI') FROM DUAL WHERE EXISTS (SELECT ASP.ASP_AIRSPACE_NM FROM c_user.AIRSPACE ASP WHERE ASP.ASP_AIRSPACE_NM = $1 )" PL/pgSQL function "create_airspace_availability_record" line 23 at SQL statement Why isn't c_user being replaced with my param (user1)?

    Read the article

  • Database design grouping contacts by lists and companies

    - by Serge
    Hi, I'm wondering what would be the best way to group contacts by their company. Right now a user can group their contacts by custom created lists but I'd like to be able to group contacts by their company as well as store the contact's position (i.e. Project Manager of XYZ company). Database wise this is what I have for grouping contacts into lists contact [id_contact] [int] PK NOT NULL, [lastName] [varchar] (128) NULL, [firstName] [varchar] (128) NULL, ...... contact_list [id_contact] [int] FK, [id_list] [int] FK, list [id_list] [int] PK [id_user] [int] FK [list_name] [varchar] (128) NOT NULL, [description] [TEXT] NULL Should I implement something similar for grouping contacts by company? If so how would I store the contact's position in that company and how can I prevent data corruption if a user modifies a contact's company name. For instance John Doe changed companies but the other co-workers are still in the old company. I doubt that will happen often (might not even happen at all) but better be safe than sorry. I'm also keeping an audit trail so in a way the contact would still need to be linked to the old company as well as the new one but without confusing what company he's actually working at the moment. I hope that made sense... Has anyone encountered such a problem? UPDATE Would something like this make sense contact_company [id_contact_company] [int] PK [id_contact] [int] FK [id_company] [int] FK [contact_title] [varchar] (128) company [id_company] [int] PK NOT NULL, [company_name] [varchar] (128) NULL, [company_description] [varchar] (300) NULL, [created_date] [datetime] NOT NULL This way a contact can work for more than one company and contacts can be grouped by companies

    Read the article

  • Need help to create database schema for wholesale online tee store

    - by techiepark
    Hi, I'm currently working on wholesale online t-shirt shop. I have done this for fixed quantity and price, and its working fine. Now i need to do this for variable quantity and price. Here is the reference link, like what i have to do. Basic tables i have created are - CREATE TABLE attribute ( attribute_id int(11) NOT NULL auto_increment, name varchar(100) NOT NULL, PRIMARY KEY (attribute_id) ); CREATE TABLE attribute_value ( attribute_value_id int(11) NOT NULL auto_increment, attribute_id int(11) NOT NULL, value varchar(100) NOT NULL, PRIMARY KEY (attribute_value_id), KEY idx_attribute_value_attribute_id (attribute_id) ); CREATE TABLE product ( product_id int(11) NOT NULL auto_increment, name varchar(100) NOT NULL, description varchar(1000) NOT NULL, price decimal(10,2) NOT NULL, image varchar(150) default NULL, thumbnail varchar(150) default NULL, PRIMARY KEY (product_id), FULLTEXT KEY idx_ft_product_name_description (name,description) ); CREATE TABLE product_attribute ( product_id int(11) NOT NULL, attribute_value_id int(11) NOT NULL, PRIMARY KEY (product_id,attribute_value_id) ); I'm not getting how to store the price based on variable quantity. Please help me to create product and its related tables. my requirement is same as above reference link.

    Read the article

  • Stored procedure strange error when called through php

    - by ravi
    I have been coding a registration page(login system) in php and mysql for a website. I'm using two stored procedures for the same. First stored procedure checks wether the email address already exists in database.Second one inserts the user supplied data into mysql database. User has EXECUTE permission on both the procedures.When is execute them individually from php script they work fine. But when i use them together in script second Stored procedure(insert) not working. Stored procedure 1. DELIMITER $$ CREATE PROCEDURE reg_check_email(email VARCHAR(80)) BEGIN SET @email = email; SET @sql = 'SELECT email FROM user_account WHERE user_account.email=?'; PREPARE stmt FROM @sql; EXECUTE stmt USING @email; END$$ DELIMITER; Stored procedure 2 DELIMITER $$ CREATE PROCEDURE reg_insert_into_db(fname VARCHAR(40), lname VARCHAR(40), email VARCHAR(80), pass VARBINARY(32), licenseno VARCHAR(80), mobileno VARCHAR(10)) BEGIN SET @fname = fname, @lname = lname, @email = email, @pass = pass, @licenseno = licenseno, @mobileno = mobileno; SET @sql = 'INSERT INTO user_account(email,pass,last_name,license_no,phone_no) VALUES(?,?,?,?,?)'; PREPARE stmt FROM @sql; EXECUTE stmt USING @email,@pass,@lname,@licenseno,@mobileno; END$$ DELIMITER; When i test these from php sample script insert is not working , but first stored procedure(reg_check_email()) is working. If i comment off first one(reg_check_email), second stored procedure(reg_insert_into_db) is working fine. <?php require("/wamp/mysql.inc.php"); $r = mysqli_query($dbc,"CALL reg_check_email('[email protected]')"); $rows = mysqli_num_rows($r); if($rows == 0) { $r = mysqli_query($dbc,"CALL reg_insert_into_db('a','b','[email protected]','c','d','e')"); } ?> i'm unable to figure out the mistake. Thanks in advance, ravi.

    Read the article

  • Procedure or function AppendDataCT has too many arguments specified

    - by salvationishere
    I am developing a C# VS 2008 / SQL Server website application. I am a newbie to ASP.NET. I am getting the above compiler error. Can you give me advice on how to fix this? Code snippet: public static string AppendDataCT(DataTable dt, Dictionary<int, string> dic) { string connString = ConfigurationManager.ConnectionStrings["AW3_string"].ConnectionString; string errorMsg; try { 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; } conn2.Open(); cmd.ExecuteNonQuery(); It errors on this last line here. And here is that SP: ALTER PROCEDURE [dbo].[AppendDataCT] @col1 VARCHAR(50), @col2 VARCHAR(50), @col3 VARCHAR(50) AS BEGIN SET NOCOUNT ON; DECLARE @TEMP DATETIME SET @TEMP = (SELECT CONVERT (DATETIME, @col3)) INSERT INTO Person.ContactType (Name, ModifiedDate) VALUES( @col2, @TEMP) END

    Read the article

  • Integer Surrogate Key?

    - by CitadelCSAlum
    I need something real simple, that for some reason I am unable to accomplish to this point. I have also been unable to Google the answer surprisingly. I need to number the entries in different tables uniquely. I am aware of AUTO INCREMENT in MySQL and that it will be involved. My situation would be as follows If I had a table like Table EXAMPLE ID - INTEGER FIRST_NAME - VARCHAR(45) LAST_NAME - VARCHAR(45) PHONE - VARCHAR(45) CITY - VARCHAR(45) STATE - VARCHAR(45) ZIP - VARCHAR(45) This would be the setup for the table where ID is an integer that is auto-incremented every time an entry is inserted into the table. The thing I need is that I do not want to have to account for this field when inserting data into the database. From my understanding this would be a surrogate key, that I can tell the database to automatically increment and I do not have to include it in the INSERT STATEMENT so instead of INSERT INTO EXAMPLE VALUES (2,'JOHN','SMITH',333-333-3333,'NORTH POLE'.... I can leave out the first ID column and just write something like INSERT INTO EXAMPLE VALUES ('JOHN','SMITH'.....etc) Notice I Wouldnt have to define the ID column... I know this is a very common task to do, but for some reason I cant get to the bottom of it. I am using MySQL, just to clarify. Thanks alot

    Read the article

  • multi-part identifier could not be bound error

    - by vishal Shah
    Here is my query: IF OBJECT_ID('NPWAS1513.dbo.usp_MSPEX_QLK_Billing_Fact_Load') IS NOT NULL DROP PROCEDURE dbo.usp_MSPEX_QLK_Billing_Fact_Load; GO CREATE PROCEDURE usp_MSPEX_QLK_Billing_Fact_Load @create_timestamp datetime, @update_timestamp datetime, @create_user varchar(50), @update_user varchar(50), @dbProdServ varchar(50) AS print 'dbProdServ is:'+ @dbProdServ; print 'current_user is:' +@current_user; DECLARE @sSQL AS VARCHAR(MAX); SET @sSQL = '' SET @sSQL = 'set identity_insert ' + @dbProdServ + '.mspex_qlk_billing_fact ON' EXEC(@sSQL); SET @sSQL = 'INSERT INTO ' + @dbProdServ +'.mspex_qlk_billing_fact (project_id, billing_year, billing_month, billing_month_desc, billing_date_id, projected_bill_amount, billed_year_to_date_amount, billed_inception_to_date_amount, remaining_bill_amount, actual_billed_amount, current_billing_percent, previous_billing_percent, billing_pct_diff, billing_type, final_bill_ind, last_in_progress_date, current_record_ind, load_time_stamp, total_contract_period, contract_period_current_year, partial_bill, create_timestamp, create_user, update_timestamp, update_user) SELECT project_dim.project_id, billing_final_data.billingyear, billing_final_data.billingmonth, billing_final_data.billingmonthdesc, Time_Dim.Time_ID, billing_final_data.projected_bill_amount, billing_final_data.billed_year_todate_amount, billing_final_data.billed_inception_todate_amount, billing_final_data.remaining_bill_amount, billing_final_data.actual_billed_amount, billing_final_data.current_billing_percent, billing_final_data.previous_billing_percent, billing_final_data.billing_pct_diff, billing_final_data.billing_type, billing_final_data.final_bill_ind, billing_final_data.last_in_progress_date, billing_final_data.current_record_ind, billing_final_data.load_time_stamp, billing_final_data.[Total Contract Period], billing_final_data.[Contract Period Current Year], billing_final_data.[Partial Bill],'''+ CAST(@create_timestamp as varchar(max)) + ''',''' + @create_user + ''','''+ CAST(@update_timestamp as varchar(50)) +''','''+ @update_user + ''' FROM '+ @dbProdServ +'.mspex_qlk_project_dim project_dim,'+ @dbProdServ +'.mspex_rpt_billing_final_data billing_final_data,'+ @dbProdServ + '.MSPEX_QLK_Time_Dim Time_Dim WHERE project_dim.myproject_project_uid = billing_final_data.projectuid AND'''+ convert(datetime, cast(billing_final_data.[BillingMonth] as nvarchar(2)) + '''/01/''' + cast(billing_final_data.[billingyear] as nvarchar(4)), 101) +''' + = Time_Dim.Time_Date'; BEGIN TRANSACTION EXEC(@sSQL) COMMIT TRANSACTION I get the error msg: Msg 4104, Level 16, State 1, Procedure usp_MSPEX_QLK_Billing_Fact_Load, Line 23 The multi-part identifier "mspex_rpt_billing_final_data.BillingMonth" could not be bound. Msg 4104, Level 16, State 1, Procedure usp_MSPEX_QLK_Billing_Fact_Load, Line 23 The multi-part identifier "billing_final_data.billingyear" could not be bound. Msg 207, Level 16, State 1, Procedure usp_MSPEX_QLK_Billing_Fact_Load, Line 83 Invalid column name 'BillingMonth'. Msg 207, Level 16, State 1, Procedure usp_MSPEX_QLK_Billing_Fact_Load, Line 84 Invalid column name 'billingyear'. I checked the column names, etc. and things are fine. In fact, I directly dragged the table name and column name to ensure that it is correct. Please help ASAP. Calling me at cell at 630-338-9427 would be great. But an URGENT response is absolutely necessary. Thanks guys.

    Read the article

  • DB2 Child Table Not Working - Create Table

    - by gamerzfuse
    I have a bit of a task before me. (DB2 Database) I need to create a table that will be a child table (is that what it is called in SQL?) I need it so that it has a foreign key constraint with my other table, so when the parent table is modified (record deleted) the child table also loses that record. Once I have the table, I also need to populate it with the data from the other table (if there is an easy way to UPDATE this). If you could point me in the right direction, this would help alot, as I do not even know what syntax to look for. Thanks in advance The table I have in place: create table titleauthors ( au_id char(11), title_id char(6), au_ord integer, royaltyshare decimal(5,2)); The table I am creating: create table titles ( title_id char(6), title varchar(80), type varchar(12), pub_id char(4), price decimal(9,2), advance decimal(9,2), ytd_sales integer, contract integer, notes varchar(200), pubdate date); I need the title_id to be matched with the title_id from the parent table AND use the ON DELETE CASCADE syntax to delete when that table is deleted from. My Attempt: CREATE TABLE BookTitles ( title_id char(6) NOT NULL CONSTRAINT BookTitles_title_id_pk REFERENCES titleauthors(title_id) ON DELETE CASCADE, title varchar(80) NOT NULL, type varchar(12), pub_id char(4), price decimal(9,2), advance decimal(9,2), ytd_sales integer, contract integer, notes varchar(200), pubdate date) ; Thanks in advance!

    Read the article

< Previous Page | 9 10 11 12 13 14 15 16 17 18 19 20  | Next Page >