Cannot Update 1 Of 2 Tables - Dynamic SQL Generation Is Not Supported
Jan 14, 2008
Hi, I'm having a problem with my code,
I am doing the following - retrieving a field from a table, which is linked to another table, i'm only updating one of the fields in one of the two tables...
Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not return any key column information.
I am getting the above error if i try to create a update command through a Command builder in .net cf on a SQLCE 3.0 database
The Select query I used for creating the update command is 'SELECT * FROM Users'
I populated a datatable with the above query through a DataAdapter, to check for the primary key and the primary key was available in the table. But still the CB could not able to create an Update Command for that query,
The Primary Key column that I use is of type GUID
Then when try to do the above job using a Typed DataSet with TableAdapters , then it throws the following error
'Update requires a valid UpdateCommand when passed DataRow Collection with modified rows'
Hey, I changed the database name in the initial cataloge in the web.config conncetion string so that it now connects to other databas that contains same tables as the old one,but now i am getting that error at the update stmt ! thank u in advance Hiba
Hi Everybody,I have a probs with dynamic generation.I am writing the probs======================================create proc testasdeclare @query varchar(500)set @query = 'select * from table'----------------------------------------------declare mycur Cursor for Select * from table |open mycur |----------------------------------------------but instate of above block how can I dynamically generate this query?---------------------------------------declare mycur Cursor for exec (@query) |---------------------------------------Or tell me the way.RegardsArijit Chatterjee
Hi all,I am following the procedure where I generate XMLs of tables and put itin a DataSet and read that dataset back into another database to bewritten into the tables.Although I am VERY close to completion a small problem that I am facingis that the XMLs being generated have as the table name "table" and notthe actual names.Is this a known issue or am I amiss? and, does anyone have a solutionfor this?Thank you.*** Sent via Developersdex http://www.developersdex.com ***
I have been working on a Human Resource Management software in C# .NET. In its Employee Attendance module i need to keep records of attendance of all workers for one month in a single table.The problem I encounter is to auto generate an exact copy of the Attendance table after a particular month is finished. How can i accomplish this? I use SQL server 2008.
I have an issue in generating the report in sql reporting services. I need to display a report in a table format. The datas of the table should be from two different sql tables. I have tried to write a stored procedure that returns two result sets from two different tables. As reporting services takes datas only from the first result set, i tried to write two different stored procedures each displays one result set. Then i have created two datasets with that two different stored procedure. Even then i cannot proceed as i was not able to use two different dataset in a single table because i was setting the datasetname to one dataset, when i try to retrieve the fields from another dataset i was able to retrieve only first and count values. Then i tried using sub reports. As sub reports for a dataregion(table) repeats for every row of the main report i was not able to fetch the correct datas. Atlast i have tried combining the query using join and wrote a single stored procedure. This stored procedure returns a single result set retrieves data from two tables satisfying the conditions. The issue i am facing with this is, the first table has only one row satisfying the condition and the second table has three rows satisfying the same condition, as i am using join query for the three rows returned by the second table the first table datas are getting duplicated for the rest of the rows in the second table. As I found using join query is the only resolution for the output which I need, and also I have to avoid the duplication of the records. Hence let me know for any solutions.
I have shown the sample datas that is duplicating which is indicated as bold. Phonenumber, Attemptdate and calloutcome are from first table and start time and endtime is from second table. As there are three different datas for the second table, first table datas are duplicated
I'm creating my first Report Model and I've managed to get through it, but if I select the "Update model statistics before generating" in the "Report Model Wizard", I get this error:
"Specified method is not supported"
(It would be a little less frustrating if it actually HAD specified the method <s>)
I seem to have a strange problem when applying a snapshot when the tables in the publication have been updated while the snapshot was being generated.
Say for example there is a table called RMAReplacedItem in the publication. When the snapshot starts being applied to the subscriber, a stored procedure called sp_MSins_RMAReplacedItem_msrepl_css gets created that handles an insert if the row already exists (ie it updates the row rather than inserting it). However, after all the data has been loaded into the tables, instead of calling this procedure, it tries to call one called sp_MSins_RMAReplacedIte_msrepl_cssm - it takes the last letter of the table name and adds it to the end of the procedure name.
The worst part is that this causes the application of the snapshot to fail, but it doesnt report what the error is, and instead it just tries applying the snapshot again. The only way i have managed to find which call is failing is to run profiler against the subscriber while the snapshot is being applied and see what errors.
I have run sp_broswereplcmds and the data in there is what is applied to the subscriber - ie the wrong procedure name.
All the servers involved are running sql 2005 service pack 2. The publisher and subscriber were both upgraded from sql 2000, but the distribution server is a fresh install of sql 2005.
Firstly I consider myself quite an experienced SQL Server user, andamnow using SQL Server 2005 Express for the main backend of mysoftware.My problem is thus: The boss needs to run reports; I have designedthese reports as SQL procedures, to be executed through an ASPapplication. Basic, and even medium sized (10,000+ records) reportingrun at an acceptable speed, but for anything larger, IIS timeouts andquery timeouts often cause problems.I subsequently came up with the idea that I could reduce processingtimes by up to two-thirds by writing information from eachcalculationstage to a number of tables as the reporting procedure runs..ie. stage 1, write to table xxx1,stage 2 reads table xxx1 and writes to table xxx2,stage 3 reads table xxx2 and writes to table xxx3,etc, etc, etcprocedure read final table, and outputs information.This works wonderfully, EXCEPT that two people can't run the samereport at the same time, because as one procedure creates and writesto table xxx2, the other procedure tries to drop the table, or read atable that has already been dropped....Does anyone have any suggestions about how to get around thisproblem?I have thought about generating the table names dynamically using'sp_execute', but the statement I need to run is far too long(apparently there is a maximum length you can pass to it), and evenbreaking it down into sub-procedures is soooooooooooooooo timeconsuming and inefficient having to format statements as strings(replacing quotes and so on)How can I use multiple tables, or indeed process HUGE procedures,withdynamic table names, or temporary tables?All answers/suggestions/questions gratefully received.Thanks
I want to retrieve the last update time of database. Whenever any update or delete or insert happend to my database i want to store and retrieve that time.
I know one way is that i have to make a table that will store the datetime field and system trigger / trigger that can update this field record whenever any update insert or deletion occur in database.
But i don't know exactly how to do the coding for this?
iden nam status ----------- -------- -------------------- 1 pp NULL 1 kk NULL 2 rr NULL 2 nn NULL 2 jj NULL 3 hh NULL
now i want to update the status cloumn in this table in such a way that the status colum = 'Status is' + iden + nam for all distinct values of iden from the table
Hello folks!I'm have some trouble with a dynamic update system! What I want to do: 1. I want to send in the code behind from any .aspx file values and parameters to a .vb class2. Code (code behind in .aspx file):1 gridupdate.updategrid("tblFeedbackA", e.CommandArgument, "locked=@locked", "@locked", "int", "0") 'Call de .vb class2 getgridfeedback() 3. Code (code in .vb class)1 Public Shared Function updategrid(ByVal tblnaam As String, ByVal x As Integer, ByVal sql As String, ByVal parameters As String, ByVal sqltype As String, ByVal waarden As String 'translation: values) 2 Dim dynstr As String() 3 Dim dynstr2 As String() 4 Dim re As New Regex(",") 5 dynstr = re.Split(parameters) 6 Dim i As Integer 7 dynstr2 = re.Split(sqltype) 8 Dim dynstr3 As String() 9 dynstr3 = re.Split(waarden) 10 11 Dim sqlconn As New SqlConnection(ConfigurationManager.ConnectionStrings("DataBase").ConnectionString) 12 Dim sql2 As String = "UPDATE " & HttpContext.Current.Session("prefix").ToString & tblnaam & " set " & sql & " where id=" & x 13 Dim sqlcmd As New SqlCommand(sql2, sqlconn) 14 sqlconn.Open() 15 16 For i = 0 To dynstr.Length - 1 17 sqlcmd.Parameters.Add(dynstr(i), CType("sqldbtype." & dynstr2(i), System.Data.SqlDbType)) 18 sqlcmd.Parameters(dynstr(i)).Value = dynstr3(i) 19 Next 20 sqlcmd.ExecuteNonQuery() 21 sqlconn.Close() 22 Return Nothing 23 End FunctionAll I want to do is to add the sqlparameters dynamically, but I don't find a way to do this :).Can you help me out?Thanks!
We have 20 -30 normalized tables in our dartabase . Also we have 4tables where we store the calculated data fron those normalised tables.The Reason we have these 4 denormalised tables is when we try to dothe calcultion on the fly, our site becomes very slow. So We haveprecalculated and stored it in 4 tables.The Process we use to do the precalcultion, will get do thecalculation and and store it in a temp table. It will compare the thetemp with denormalised tables and insert new rows , delte the old oneans update if any changes.This process take about 20 mins - 60mins. Ittakes long time because in this process we first do the calculationregardless of changes and then do a compare to see what are changed andremove if any rows are deleted, and insert new rowsand update thechanges.Now we like to capture the rows/columns changed in the normalisedtables and do only those chages to the denormalised table , which weare hoping will reduce the processing time by atleast 50%WE have upgraded to SQL SERVER 2005.So We like to use the newtechnology for this process.I have to design the a model to capture the changes and updated onlythose changes.I have the list of normalised tables and te columns which will affectthe end results.I thought of using Triggers or OUTPUT clause to capture the changes.Please help me with the any ideas how to design the new process
Thank you Darrell for your help on my "Firehose" problem.
Well, I have another question for everyone. I have three tables with the same columns: Products, Products_Sold, and Products_StandBy. I have a Stored Procedures that gets the products: Products_Get, Products_Sold_Get, and Products_StandBy_Get. I want to be able to only have one stored procedure that gets from all tables depending on what @Table variable I give it.
In Dot net 2.0 we change using SQLDataSource to Conect with SQLDB. Now for My case ,the Select SQL is dynamic when differnece user and parameters to the page, So if I want to Update the data input by user,then I must give Update/insert/delelte SQL to SQLDatasource's InsertCommand /UpdateCommand/DeleteCommand . How to Generate the Insert/update/delete command for the SQLDataSource ? as in dot net 1.1 can use SQLCommandBuilder to generate it,but SQLCommandBuilder just support DataAdeptor not for SQLDataSource, Could any body know how to do it when the SelectCommand is dynamic and need to update data back to DB after edit? thanks a lot.
Would it be possible to retrieve a "dynamically" named field from a table by using an input parameter?
For example, if a table has fields named Semester1, Semester2, Semester3, Semester4, and I was lazy and only wanted to create one stored procedure for all semesters could I do the following...
ALTER PROCEDURE u_sp_x @semester int AS Select Semester@semester From ThisTable
In general, What is the best approach in creating a dynamic updatestored procedure, that can handle recieving varying input paramters andupdate the approporiate columns.
Hi AllI have a question about generating dynmamicly If Update() statement in atrigger..in My db, there is a table that holds some column names of an another table.for example;Columns Table-A: Col1, Col2, Col3, Col4,Col5Table-B: Col2, Col5 (The selected columns of Table A)Then, in the Trigger of Table-A I use;Select name from syscolumns where id=object_id('Table-A')fetch next from TableA_Cursor into @strColNamethen, I used a statement like this..if UPDATE(' + @strColName + ')But it gives "incorrect syntax" error..How can I write this line?Thanks alot in advance...--Message posted via http://www.sqlmonster.com
HiMy problem is as follows:I need to transmit data between two databases on the same server, but Ihave to use dynamic database names (they must be configurable). Forexample I need to achive sth like that:insert into [database1].[dbo].[table1](select columns from [table2])when database1 is not known at implementation stage.I know I can use EXEC @t_sql_code, but I wonder if there is any otherway? (OPENROWSET doesn't seem to suit my needs)Thanks in advanceAmfi
OK, I'm trying to add some audit type information to a set of tables in my database. This involves adding 2 columns and sticking some data into those two columns. The columns themselves are added successfully, but I'm having troubles sticking any data into them - I'm getting a lot of errors. What I want to do is put a single character code in one column, and a datetime in the second. Here's the SQL I'm trying...
Conversion failed when converting datetime from character string.
I tried changing the datetime column to varchar, and CONVERT(varchar(30),@TxDateTime). That gets rid of the above error, but replaces it with the following (twice, I might add - one for each column?):
Msg 213, Level 16, State 1, Line 1
Insert Error: Column name or number of supplied values does not match table definition.
Any help is appreciated - let me know if you need more info.
I am quite new to the complexities of MS SQL and have a problem, I would like to resolve. I have 2 tables with a unique identifier in both and want to populate a new table with information from both, but the second table I would like to populate just some fields that have a DOB eg
Table 1: uniqueId Name Address
Table2: uniqueId Type Setting
example of content for Table 2: uniqueId Type Setting 123 DOB 03/04/74 234 TFN 12345678 567 POA Mr Smith
So the new table needs to be populated with a ll of info in table 1 and has a new field called DOB so only the clients with a DOB should populate this field, if the client in Table 1 has a TFN reference, this record should be added to the new table but no value needs to be entered eg
123 Chris Smith 1 high street 03/04/74 234 Jon brown 2 high terrace <Null>
Hi, I rewrote my working Sql statement to prevent Sql Injections. I copied some code I used in another project but this time I can't get it to work, possibly because it's an update statement and not an Insert one, which I used before. Sorry for the boring question, but does anyone have a clue what's wrong with the syntax? Here's the original code (I changed the parameter names for clarity and security): Dim conn As SqlConnection = New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("MyConnectionString").ConnectionString) Dim strSQL As String = "Update MyTable Set " & typ & num & " = '" & pname & "' WHERE personID = " & fid Dim cmd As SqlCommand = New SqlCommand(strSQL, conn) Here's the code from codebehind: Dim conn As SqlConnection = New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("MyConnectionString").ConnectionString) Dim strSQL As String = "Update MyTable Set (" & typ & num & ") Values (@" & typ & num & ") WHERE personID = " & fid Dim cmd As New SqlCommand(strSQL, conn) With cmd.Parameters .Add(New SqlParameter("@" & typ & num, pname)) End With TestLabel.Text = strSQL & " " & pname cmd.Connection.Open() cmd.ExecuteNonQuery() cmd.Connection.Close() Here's my test message; first the sql, then the new string to be inserted: Update MyTable Set (picturename) Values (@pname) WHERE personID = 2 2_adin.jpg Here's my error code: Line 1: Incorrect syntax near '('. 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.Data.SqlClient.SqlException: Line 1: Incorrect syntax near '('. Source Error: Line 489: TestLabel.Text = strSQL & " " & pnameLine 490: cmd.Connection.Open()Line 491: cmd.ExecuteNonQuery()Line 492: cmd.Connection.Close()Line 493: End If I could understand it if I'd get an error in VWD Express for using dynamic variables, but they work correctly in the text message so I'm clueless. Any help is deeply appreciated! Pettrer (VB, Sql Server 2000)
I'm trying to generate an update statement based off select statement results. A very basic example,
SELECT ListID FROM DListing WHERE Status = 2Results return 3 rows. 1234 2345 3456
How can I take those results and turn them into WHERE criteria for UPDATE statement?
Generated UPDATE statement should look like this.
UPDATE DListing SET Status = 1 WHERE ListID IN (1234,2345,3456)
I have started by creating a temp table to hold my SELECT results, but I don't know how to get those results into format for IN condition. Right now I get 3 UPDATE statements with 1 ListID in each IN condition.
CREATE TABLE #TempStatusUpdate(ListID INT) INSERT INTO #TempStatusUpdate SELECT ListID FROM DListing WHERE Status = 2 SELECT 'UPDATE DListing SET Status = 1 WHERE ListID IN (' + CONVERT(VARCHAR(30),ListID) + ') AND Status = 2' DROP TABLE #TempStatusUpdate
Hi: I'm trying to create an ad-hoc query on a Asp.net page for user. Besides the usual Boolean operators, Field Names, Comparison operators & Field Values, the ad-hoc query also involves multiple tables, eg [Customers] , [Members] & [Orders].
Now I have difficulties on writing a TSQL sp on how to take the dynamic query with different tables under consideration. User might simply query each individual tables (eg, Customers with age > 25) or combination of tables (eg, Membered Customers with Orders Amt > 1000 between 1/1/2005 - 1/31/2005)
I have look up a lot dynamic query on the net but all are with only 1 single table to hit. Could anyone give me a direction on how to write a dynamic query script with multiple tables under consideration? Much appreciated.
ps: The ad-hoc query only contains these defined tables, no other table will be involved.
I would like to do a dynamic audit for the tables ( columns which needs to audited will also change dynamically). For example,
I am having 3 tables, table1 table2 table3
User can select Table 1 ( col 1, col3, col4) and Table2 ( col 3 and col 5).
I want to achieve this functionality without any triggers or output clause, so only one option which is left is "ChangeDataCapture" ( to my knowledge). So i did a small POC. The problem here is, system captures all the field data even though value doesn't change, for example,
TableA
CountryId CountryCode CountryName 1 IND INDIA Update TableA Set CountryCode = 'INDI', CountryName = 'INDIA' Where CountryId = 1
On running the above query, CDC stores the value for both the columns, but i don't want this. I only wanted to store the CountryCode value alone.
Hi allIn the SP below im (trying to) do some dynamic sql. As you can see the tableto use is set as a variable and the 'exec' method used to run thesqlstatements.My problem is that the 'if exists' method is not doing what i was hoping itcould do.The @presql command returns somewhere between 0 or 50 rows (give and take) -i just want the 'if exists' part to determine if the select statementreturns something or not since i then will have to update a current row - orinsert a new one.Even if there is no rows returned, the 'if exists' command will return true:-/Any suggestions to a different way of approach...?Thanks in advance :-)######## Stored procedure start ########[various @ variables]....declare @presql varchar(200)select @presql = 'SELECT * FROM '+@CurrentDB+' where btsiteID='+cast(@SiteID as varchar(6))+''IF exists((@presql))BEGINdeclare @UpdateSQL varchar(400)set @UpdateSQL = 'UPDATE '+@CurrentDB+' SET btDate='''+cast(@FileDate asvarchar(12))+''''exec(@UpdateSQL)ENDELSEBEGINdeclare @InsertSQL varchar(2000)select @InsertSQL = 'INSERT INTO ' + @CurrentDB + '(btDate,btTime)VALUES('''+ cast(@FileDate as varchar(12)) + ''','+ cast(@ImportTime as varchar(6)) + ')'EXEC(@InsertSQL)END######## Stored procedure end ########
I have a database with serveral tables, for example 'customer', I want to update this table with a SSIS package. However, to ensure we don't have issues if the update fails then I've put in an intermediate stage
Using an Execute SQL Task I create temporary tables, for example 'customer_tmp'. Data is then imported into these tables. When all the data is imported successfully the original tables are dropped and the temporary tables are renamed, removing the '_tmp'
This works fine and I'm happy with it. However, if someone adds a column to one of the tables in SQL server it is lost on the next upload.
Similarly I have to hard code creating the indexes into the package as well.
Does anyone know how I could copy the original table definitions and create the temporary tables dynamically. So that any new columns would be picked up?
And indeed is it possible to copy the indexes from one table to another before the drop and rename trick?
it seems like i am able to create it. But when i try to access that temporary table, i get an error "Invalid object". this is happening only when i try to create local temporary table. Global temporary table works fine inside the dynamic SQL.