MS SQL Server 7: Deletion Of Child Records.
Hello All,
I have been involved in a project wherein i have to delete old records from two table and the corresponding child records from the interlinked tables.
I try to find a SQL Procedure that deletes the child records, but that procedure uses the sysforeignkeys table for recursively deleting the child records.
When i looked at my sysoreignkeys table, it was empty(no rows).
Request you all if you can provide me the SQL Procedure that can delete record in the table with the child records.
Thanks in advance
Regards,
Manoj Kumar
View Complete Forum Thread with Replies
Related Forum Messages:
Deletion Of Parent And Child Table
how can we delete parent table as well as child table using a single query applied on parent table, can someone please help me onn this topic? it will be very nice of you guys. Rahul Arora 07 Batch NCCE Israna, ###################### IMPOSSIBLE = I+M+POSSIBLE
View Replies !
Daily Deletion Of Records
Ladys, Gentlement, I have table that grows anywhere from 200,000 to 1,000,000 records perday. Besides that I need to keep at least 6 months historical data from this same table. The transaction log was purged after each batch when testing data monthly. I'm looking for some way of deleting just one day's data if it meets a criteria. It must remain within the 6 months period of historical data. This is what I've come up with so far" select * FROM dbo.Temp_table WHERE datediff(day, DATE_TIME, getdate()) >= 180 If it meets this criteria I can change the select to a delete? Please Let me know what you think
View Replies !
Auto Deletion Of Records Sqlserver
Hi I am not sure if I am at right place, anyhow I hope I am :) Now the question: I am using an ASP.net Application with SQL-Server. I want to make a page so that it set the expiration time (date) for certain record and once that time reaches, it deletes those records, or make any updates to the record (what ever applicable). I also want to control this auto deletion from my application, means that turn this On/Off whenever needed. I am not sure how to start this. I was told by a friend that I need to use triggers from SQL-server but I need some help. Can anyone help me out on this? RegardsMykhan
View Replies !
Insertion And Deletion Of Records Inside A Single Stored Procedure
Hi, I have two tables A and B. In table A i have three columns called empid, empname and empsalary where empid is an identity column. Table A has some records filled in it. Table B has the same schema except the fact that the empid is not an identity column in table B. Table B does not contain any rows initially. All other aspects remain the same as that of table A. Now i am going to delete some records in table A based on the empid. When i delete the records in table A based on empid the deleted records should be inserted into table B with the same empid. I need to accomplish these two tasks in a single stored procedure. How to do it? I need the entire code for the stored procedure. Please help me. I am trying for the past 4 days. Thanx in Advance
View Replies !
Update Child Records Help
Please help I have table1 which has many unique ID numbers and table2 that has many records for each ID. some of the ID numbers in table1 have changed and I have created a translation table (table3) that links the old and new ID numbers. What I need to do is some sort of update sql statement that updates all the records in table2 changing all the oldID numbers to the new ones using the translation table. Table1 and table2 are not linked...can anyone help me with the sql statement example Table 1 IDNUM NAME 12345 Joe 12346 Mary 12347 David Table2 IDNUM FIELD1 12345 hello 12345 goodbye 12346 hello 12347 goodbye 12346 hello 12346 goodbye Table3 OLDID NEW ID 12345 54321 12347 74321 need to change the IDNUM in Table2 to 54321 where IDNUM = 12345 and same with 12347..Need to do this for many many IDs but not all. Thanks very much
View Replies !
Inserting Master And Child Records
Hi, I need to insert a record in a master table and 20 records in a child table. I want to do this using stored procedure. Is it better to do it in stored procedure? Have somebody already tried this? Or is there any sample that I can use? Thanks a lot!
View Replies !
Insert Parent Child Records...
Hello, We have a complex functionality of migrating data from a single record into multiple parent child tables. To give you an example, lets us assume that we have a single table src_orders in the source database. We have a parent Order table and a child OrderDetails table in the target database. We need to pick one row from src_orders and insert this row in the Order table, pick up its PK (which is an identity column) and then use this to insert rows (say 5) in the OrderDetails table. Again, we go back to the source, take a row, insert it into Orders, pick up the Orders PK and insert n rows in OrderDetails. As of now, we are using the following approach for achieving this functionality. 1. Get the identity generated from the target table and store both the source table id and the target table id in a recordset. 2. Use the recordset as the source to a foreachloop , using foreachADO enumerator 3. Use data flow tasks to get the fields from the parent table for the source id, that needs to be inserted into the target child table In case I have not ended up confusing everyone, can anyone validate this or suggest a better approach? :) Thanks, Satya
View Replies !
Parent And Child Records From Same Table
Hi i have a table named categorymaster categoryid catname parentid 1 Boxing 0 2 Tennis 0 3 Basketball 0 4 MayWeather 1 5 Tyson 1 6 Clinton woods 1 7 RogerFederer 2 8 Micheal 3 9 Hingis 2 so if i give input say categoryid=1[This falls under main category-boxing] i need to get result as 1 boxing [main category] 4 mayweather [sub category] 5 tyson [sub category] 6 clinton woods [sub category] if i give categoryid=5[Note:Tyson] result should be as 1 boxing [main category] 5 tyson [sub category] hope u can get my question Thanks in advance
View Replies !
How To Trace The Records That Have Been Related To The Child Table
The problem of mine is, I have a datagrid, Which displays data from a Employee(parent) table. Now I want to delete some records based on the user selected checkbox,only those records which has no related records in the EmployeeProject(child) can be deleted.I want to know which are all the record that cannot be deleted? How can I achieve this?
View Replies !
Selecting TOP X Child Records For A Parent Record
Hi,I have a stored procedure that has to extract the child records forparticular parent records.The issue is that in some cases I do not want to extract all the childrecords only a certain number of them.Firstly I identify all the parent records that have the requird numberof child records and insert them into the result table.insert into t_AuditQualifiedNumberExtractDetails(BatchNumber,EntryRecordID,LN,AdditionalQualCritPassed)(select t1.BatchNumber,t1.EntryRecordID,t1.LN,t1.AdditionalQualCritPassedfrom(select BatchNumber,RecordType,EntryRecordID,LN,AdditionalQualCritPassedfrom t_AuditQualifiedNumberExtractDetails_Temp) as t1inner join(select BatchNumber,RecordType,EntryRecordID,Count(*) as AssignedNumbers,max(TotalNumbers) as TotalNumbersfrom t_AuditQualifiedNumberExtractDetails_Tempgroup by BatchNumber, RecordType, EntryRecordIDhaving count(*) = max(TotalNumbers)) as t2on t1.BatchNumber = t2.BatchNumberand t1.RecordType = t2.RecordTypeand t1.EntryRecordID = t2.EntryRecordID)then insert the remaining records into a temp table where the number ofrecords required does not equal the total number of child records, andthenloop through each record manipulating the ROWNUMBER to only selectthe number of child records needed.insert into @t_QualificationMismatchedAllocs([BatchNumber],[RecordType],[EntryRecordID],[AssignedNumbers],[TotalNumbers])(select BatchNumber,RecordType,EntryRecordID,Count(*) as AssignedNumbers,max(TotalNumbers) as TotalNumbersfrom t_AuditQualifiedNumberExtractDetails_Tempgroup by BatchNumber, RecordType, EntryRecordIDhaving count(*) <max(TotalNumbers))SELECT @QualificationMismatched_RowCnt = 1SELECT @MaxQualificationMismatched = (select count(*) from@t_QualificationMismatchedAllocs)while @QualificationMismatched_RowCnt <= @MaxQualificationMismatchedbegin--## Get Prize Draw to extract numbers forselect @RecordType = RecordType,@EntryRecordID = EntryRecordID,@AssignedNumbers = AssignedNumbers,@TotalNumbers = TotalNumbersfrom @t_QualificationMismatchedAllocswhere QualMismatchedAllocsRowNum = @QualificationMismatched_RowCntSET ROWCOUNT @TotalNumbersinsert into t_AuditQualifiedNumberExtractDetails(BatchNumber,EntryRecordID,LN,AdditionalQualCritPassed)(select BatchNumber,EntryRecordID,LN,AdditionalQualCritPassedfrom t_AuditQualifiedNumberExtractDetails_Tempwhere RecordType = @RecordTypeand EntryRecordID = @EntryRecordID)SET @QualificationMismatched_RowCnt =QualificationMismatched_RowCnt + 1SET ROWCOUNT 0endIs there a better methodology for doing this .....Is the use of a table variable here incorrect ?Should I be using a temporary table or indexed table if there are alarge number of parent records where the child records required doesnot match the total number of child records ?
View Replies !
Writing Parent/Child Records To Flat File
I have a set of parent/child records that need to be exported to a space delimited Flat File. Each parent record must be followed by 3 child records, each on their own line with different format. I have a prototype using the Derived Column component that concatinates the various fields of each record into one "wide" text column. This fools SSIS to think that each row has the same format. Then I merge them together using an artificial sort id. But this seems overly tedious and very brittle. What would be the best approach to writing these records out? I'm hoping there is a better more maintainable method. Thanks, Jon
View Replies !
How To Calculatesave A Parent Status Based On Related Child Records
Thanks for your time, How to calculate & save a Parent status [qcStatus varchar(30)] and Alert [alertFlag bit] in dbo.a1_qcParent based on comparison of its Child records in dbo.a3_qcItems2Fix columns [itemComplete bit] and [alertFlag bit] Where a1_qcParent[a1_id] = a3_qcItems2Fix[a1_ID] - Parent CLOSED: if all children [itemComplete] are True - Parent OPEN: if any child [itemComplete] is False - Parent ALERT: True if any child row [alertFlag bit] is True Using sql_Datasource in webpage, but more comfortable in sql... After-Trigger? Can Parent columns have calculated formula referencing the child table? Please help.
View Replies !
Writing Trigger To Insert Records Into Master And Child Table At A Time ?
I am developing an application in vb.net 2005 using SQL Server 2000. In this I have two tables SessionMaster and SessionChild. Fields of session master - SessionMastId, Start_Date, End_Date, Session_Type, Fields of session child - SessionChildId, SessionMastId, UserName, Comment. SessionMastId and SessionChildId are primary keys of respective tables and also they are auto increment fields. Please how to write trigger to insert record into both tables at a time.
View Replies !
Help With How To Send E-Mail (Parent - Child Matching Records) From SQL 2005 Stored Procedure.
Folks,Using NorthWind as Example: Parent Table derived from: Categories. I added a new Column E-Mail and Selecting rows where Category Id <=3. Here is my Data. Category ID Category Name Category E-mail 1 Beverages Beverages.com 2 Condiments Condiments.com 3 Confections Child Table derived from: Products. I am Selecting rows where Category Id <=3. Here is my Sample Data. Category ID Product Name Quantity Per Unit 1 Chang 24 - 12 oz bottles 1 Côte de Blaye 12 - 75 cl bottles 1 Ipoh Coffee 16 - 500 g tins 1 Outback Lager 24 - 355 ml bottles 2 Aniseed Syrup 12 - 550 ml bottles 2 Chef Anton's Gumbo Mix 36 boxes 2 Louisiana Hot Spiced Okra 24 - 8 oz jars 2 Northwoods Cranberry Sauce 12 - 12 oz jars 3 Chocolade 10 pkgs. 3 Gumbär Gummibärchen 100 - 250 g bags 3 Maxilaku 24 - 50 g pkgs. 3 Scottish Longbreads 10 boxes x 8 pieces 3 Sir Rodney's Scones 24 pkgs. x 4 pieces 3 Tarte au sucre 48 piesI would like to read 1st Category Id, Category E-Mail from Categories Table (ie. Category Id = 1), find that in Products Table. If match, extract matching records for that Category from Both Tables (Categories.CategoryID, Products.ProductName, Products.QuantityPerUnit) and e-mail them based on E-Mail Address from Parent (Categories ) Table. If no E-Mail Address is listed, do not create output file. In this instance Category Id = 3.Basically I want to select 1st record from Parent Table (Here is Category) and search for all matching Products in Products Table. And Create an E-mail and sending just those matching records. Repeat the same process for remaining rows from Categories Table. I am expecting my E-Mail Output like this: For Category Id: 1 Category ID Product Name Quantity Per Unit 1 Chang 24 - 12 oz bottles 1 Côte de Blaye 12 - 75 cl bottles 1 Ipoh Coffee 16 - 500 g tins 1 Outback Lager 24 - 355 ml bottlesFor Category Id: 2 Category ID Product Name Quantity Per Unit 2 Aniseed Syrup 12 - 550 ml bottles 2 Chef Anton's Gumbo Mix 36 boxes 2 Louisiana Hot Spiced Okra 24 - 8 oz jars 2 Northwoods Cranberry Sauce 12 - 12 oz jarsI am not extracting the Data for any user Interface (ie. Grid View/Form View Etc). I will just create a Command Button in an ASP.NET 2.0 form to extract Data. My Tables are in SQL 2005. I was thinking to read the Category records in a Data Reader and within the While Loop, call a SP to retrieve the matching records from Products Table. If matching records found, call System SP_Mail to send the E-mail. The drawback with that for every category records (Within While Loop) I need to call my SP to get Products Data. Will be OVERKILL? Ideally I would like extract my records with one call to a SP. Is there any way I can run a while loop inside the SP and extract Child Data based on Parent Record? Any Help or sample URL, Tutorial Page will be appreciated. Thanks
View Replies !
Child,chid Of Child ,child Of Child Of Child
............child |parent|.............a1 |a | .............a2 |a |.............a11 |a1 |.............b1 |b |.............b11 |b1 |.............b111 |b1 |............. Here is my table I want to get all childs of "a" ie {a1,a11,a2}I mean recursivelyie child,chid of child ,child of child of child ........etc up to any extentet the table containHow can i for mulate the select querry?
View Replies !
Trying To Return A Single Record For Each Client From Child Table Based Upon A Field Of Date Type In Child Table
I have table "Clients" who have associated records in table "Mailings" I want to populate a gridview using a single query that grabs all the info I need so that I may utilize the gridview's built in sorting. I'm trying to return records containing the next upcoming mailing for each client. The closest I can get is below: I'm using GROUP BY because it allows me to return a single record for each client and the MIN part allows me to return the associated record in the mailings table for each client that contains the next upcoming 'send_date' SELECT MIN(dbo.tbl_clients.client_last_name) AS exp_last_name, MIN(dbo.tbl_mailings.send_date) AS exp_send_date, MIN(dbo.tbl_mailings.user_id) AS exp_user_id, dbo.tbl_clients.client_id, MIN(dbo.tbl_mailings.mailing_id) AS exp_mailing_idFROM dbo.tbl_clients INNER JOIN dbo.tbl_mailings ON dbo.tbl_clients.client_id = dbo.tbl_mailings.client_idWHERE (dbo.tbl_mailings.user_id = 1000)GROUP BY dbo.tbl_clients.client_id The user_id set at 1000 part is what makes it rightly pull in all clients for a particular user. Problem is, by using the GROUP BY statement I'm just getting the lowest 'mailing_id' number and NOT the actual entry associated with mailing item I want to return. Same goes for the last_name field. Perhaps I need to have a subquery within my WHERE clause?Or am I barking up the wrong tree entirely..
View Replies !
I Want To Transfer ONLY New Records AND Update Any Modified Records From Oracle Into SQL Server Using DTS
I need a little help here..I want to transfer ONLY new records AND update any modified recordsfrom Oracle into SQL Server using DTS. How should I go about it?a) how do I use global variable to get max date.Where and what DTS task should I use to complete the job? Data DrivenQuery? Transform data task? How ? can u give me samples. Perhaps youcan email me the Demo Package as well.b) so far, what I did was,- I have datemodified field in my Oracle table so that I can comparewith datelastrun of my DTS package to get new records- records in Oracle having datemodified >Max(datelastrun), and transferto SQL Server table.Now, I am stuck as to where should I proceed - how can I transfer theserecords?Hope u can give me some lights. Thank you in advance.
View Replies !
Deletion
Hi all, I have a table in xyz database and there is no column in table like creation_date or modified_date. The problem is I want to delete records which has been added in the table before 1st jan 2007. The size of table is 85 GB Immediate help would be appriciable. Regards, Frozen
View Replies !
Restrict Deletion
What would be the best practice to prevent users who didn't create a record in sql from deleting? When a record is created I have the username who created the record in one of the fields. I was thinking maybe a query? Thank you in advance.
View Replies !
Deletion Of Duplicate Row
Hi Everyone,I have a table in which their is record which is exactly same.I want to delete all the duplicate keeping ony 1 record in a table.ExampleTable AEmpid currentmonth PreviousmonthSupplimentarydays basic158 2001-11-25 00:00:00.000 2001-10-01 00:00:00.000 2.004701.00158 2001-11-25 00:00:00.000 2001-10-01 00:00:00.000 2.004701.00158 2001-11-25 00:00:00.000 2001-10-01 00:00:00.000 2.004701.00I want to delete 2 rows of above table.How can I achieve that.Any suggestion how can i do that.Thank you in advanceRichard
View Replies !
Replication Without Deletion
Hello there, We are currently setting up out production server to the following requirements: 1. Every month, delete records that haven't been changed in the last 90 days. 2. Replicate insert statements to a backup database which will keep track of all data, and act as an archive/data warehouse. The first step is easy, as it is just a script that checks the date of the last change on each row. However, the second step is a bit more tricky. We tried setting up replication between two test databases, but we ran into the following problem: Whenever old data has been deleted in the production database, the replication agent deletes it in the data warehouse database too. Is it possible to override or disable this, so data is only inserted/updated, and not deleted? No applications using the database deletes records, so database integrity should not be a problem. Thanks for your time, Ulrik Rasmussen
View Replies !
Deletion Problem
It is an option to set deletion without getting logged since I have problem to delete two years historical data and would like to keep this year data on my 80MB rows. Actually I create a new table to get copy one-year data and I truncated the old table. I am wondering if there is other better way to do this task. TIA, Stella Liu
View Replies !
Deletion Query
Ok, so I have an issue, was wondering if anybody else has any suggestions. I have a table that is pretty large, in all regards. It is a "message" table that holds text messages that users send to each other. 1. Has some data fields, integers, dates, some bit columns, a message subject field (varchar(250)), and a message body field (field type = text) 2. Table contains about 70 million records 3. Table has 6 indexes associated to it 4. Table has 2 views associated to it. 5. Table has 8 foreign keys associated to it. I need to delete, oh, about 90,000 records out of this 70 million record table. I am able to disable the foreign keys to this table for deletion, but that does not seem to mitigate the problem. I think the issue lies with having to update the indexes as well as the views. When I execute the select statement to retrieve the records I need to delete, it executes pretty quickly, no problems there that I can see. The issue comes when I try to delete the records, it takes way too long, and we know it. We let it run for an hour and it didn't really get anywhere. This is in a server environment, some pretty decent hardware, 8gig memory, fast SCSI drives, 8 core processors, i don't know the exact specifics, but they're not bad. Here's a DBCC SHOWCONTIG on our table DBCC SHOWCONTIG scanning 'message' table... Table: 'message' (1448040590); index ID: 1, database ID: 13 TABLE level scan performed. - Pages Scanned................................: 51602 - Extents Scanned..............................: 6486 - Extent Switches..............................: 6948 - Avg. Pages per Extent........................: 8.0 - Scan Density [Best Count:Actual Count].......: 92.83% [6451:6949] - Logical Scan Fragmentation ..................: 0.54% - Extent Scan Fragmentation ...................: 0.93% - Avg. Bytes Free per Page.....................: 93.5 - Avg. Page Density (full).....................: 98.85% DBCC execution completed. If DBCC printed error messages, contact your system administrator. This is from our dev environment which is but a portion of our production db- but I presume our production environment will have similar percentages (not necessarily the pages scanned) Any suggestions on how to delete records efficiently?
View Replies !
User Deletion Log SQL
Im using SQL enterprise manager v8, a few days ago I got a report that a user account was deleted. I was wondering what logs would point this out. I've been through the event review and i am not seeing any usefull info.
View Replies !
How To Prevent Db Deletion
Hi I want to try and protect myself from my own stupidity. I have a number of sql databases, but one is LIVE. It is easy to drop tables but I want to set something (e.g. a password) which will help prevent me from dropping tables on the live database. Any help/direction here would be appreciated.
View Replies !
Database Deletion
While performing import actions I had a system freeze, when the system returned the sessions had been closed and the database had vanished, with the help of support we recovered the database only to find that the original project ID had a suffix attached ( Original 40/0110, New 40/0110-1 ), when I try to return it to it's original numbering convention it says it has to be a unique number which suggests to me it is not deleted but hiding in the background, can the original be recovered or is it possible to renumber the recovered database, I have searched the whole of the databases and the original is nowhere to be seen.
View Replies !
DB Deletion Time
Is there an option to find out the deleted DBs on a server? ------------------------ I think, therefore I am - Rene Descartes
View Replies !
Deletion And Identity Reset
Obviously to delete all records from DB table is simple, however, I would like to make my whole Live DB pretty much empty. I've copied all my data from my test DB over to my live DB (didn't mean to but I did). I would like to remove all the data and the identity values, resetting them back at their original values. Is there a simple way or do I have to do it the hard way. That being going in and removing Identity, saving and then placing identity back on the DB Table.
View Replies !
Alert On Data Deletion
We have an employee table that contains bank details and are experiencingproblems with account numbers being erased and lost. In order to track downwhy this is happening (either due to our application code or SQLreplication) we'd like to be able to prevent certain columns from beingdeleted if they already contain some data.Is it possible to setup a check constraint to prevent our ee_acct_no columnsfrom being set to NULL or blank strings if it contains an account number(i.e a 9 digit number)? We have setup the column to allow NULL's as we don'talways know employees bank details until later, so we do need to put them onour database without bank details initially.Also, if possible, can someone suggest a stored procedure or trigger i couldcreate that would fire a user-defined error message that would email anoperator if a bank account number changed?Many thanksDan Williams.
View Replies !
Recovering From Transaction Log Deletion In 6.5
I was trying to relocate my transaction log to a bigger drive usingsp_movedevice but I made a mistake in the syntax of the second parameterand put only the path, not the path and the file name.Now my database is marked as "suspect" and I get an error message in my logupon database start up saying that the log file cannot be open.Is there a way to have MS SQL 6.5 "forget" all the logs of this database,create new ones and restart the database? The logs contained nothingimportant, I had truncated them an hour or so before I made my mistake. Ijust want to make sure the data are still usable.When I look at the devices with sp_helpdevice, I can see a log that existand is hopefully in pristine condition and the one that doesn't existanymore.I looked in the archives of various newsgroups but couldn't find somethingthat correspond closely to my situation. I saw something similar but withMS SQL 7.0(http://groups.google.com/groups?hl=...om %26rnum%3D4)using sp_attach_db/sp_detach_db. What would be the equivalent with version6.5?Thanks!Charles--Charles-E. Nadeau Ph.Dhttp://radio.weblogs.com/0111823/
View Replies !
Database Still 'exists' After Deletion
hi Basically, I create a database with sql, then I delete it manually(not via sql statment. This is a problem which I realise. In fact, you can't delete the database because the VS 2005 still is using it) I run the same code again, then it says the database still exists, even it is physically destroied. ------Here is the errors: System.Data.SqlClient.SqlException: Database 'riskDatabase' already exists. at System.Data.SqlClient.SqlConnection.OnError(SqlExc eption exception, Boolea n breakConnection) ------The evidence that the database doesn't exist physically: Unhandled Exception: System.Data.SqlClient.SqlException: Cannot open database "riskDatabase" requested by the login. The login failed. ------The code: /* * C# code to programmically create * database and table. It also inserts * data into the table. */ using System; using System.Collections.Generic; using System.Text; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.IO; namespace riskWizard { public class RiskWizard { // Sql private string connectionString; private SqlConnection connection; private SqlCommand command; // Database private string databaseName; private string currDatabasePath; private string database_mdf; private string database_ldf; public RiskWizard(string databaseName, string currDatabasePath, string database_mdf, string database_ldf) { this.databaseName = databaseName; this.currDatabasePath = currDatabasePath; this.database_mdf = database_mdf; this.database_ldf = database_ldf; } private void executeSql(string sql) { // Create a connection connection = new SqlConnection(connectionString); // Open the connection. if (connection.State == ConnectionState.Open) connection.Close(); connection.ConnectionString = connectionString; connection.Open(); command = new SqlCommand(sql, connection); try { command.ExecuteNonQuery(); } catch (SqlException e) { Console.WriteLine(e.ToString()); } } public void createDatabase() { string database_data = databaseName + "_data"; string database_log = databaseName + "_log"; connectionString = "Data Source=.\SQLExpress;Initial Catalog=;Integrated Security=SSPI;"; string sql = "CREATE DATABASE " + databaseName + " ON PRIMARY" + "(name=" + database_data + ",filename=" + database_mdf + ",size=3," + "maxsize=5,filegrowth=10%)log on" + "(name=" + database_log + ",filename=" + database_ldf + ",size=3," + "maxsize=20,filegrowth=1)"; executeSql(sql); } public void dropDatabase() { connectionString = "Data Source=.\SQLExpress;Initial Catalog=" + databaseName + ";Integrated Security=SSPI;"; string sql = "DROP DATABASE " + databaseName; executeSql(sql); } // Create table. public void createTable(string tableName) { connectionString = "Data Source=.\SQLExpress;Initial Catalog=" + databaseName + ";Integrated Security=SSPI;"; string sql = "CREATE TABLE " + tableName + "(userId INTEGER IDENTITY(1, 1) CONSTRAINT PK_userID PRIMARY KEY," + "name CHAR(50) NOT NULL, address CHAR(255) NOT NULL, employmentTitle TEXT NOT NULL)"; executeSql(sql); } // Insert data public void insertData(string tableName) { string sql; connectionString = "Data Source=.\SQLExpress;Initial Catalog=" + databaseName + ";Integrated Security=SSPI;"; sql = "INSERT INTO " + tableName + "(userId, name, address, employmentTitle) " + "VALUES (1001, 'Puneet Nehra', 'A 449 Sect 19, DELHI', 'project manager') "; executeSql(sql); sql = "INSERT INTO " + tableName + "(userId, name, address, employmentTitle) " + "VALUES (1002, 'Anoop Singh', 'Lodi Road, DELHI', 'software admin') "; executeSql(sql); sql = "INSERT INTO " + tableName + "(userId, name, address, employmentTitle) " + "VALUES (1003, 'Rakesh M', 'Nag Chowk, Jabalpur M.P.', 'tester') "; executeSql(sql); sql = "INSERT INTO " + tableName + "(userId, name, address, employmentTitle) " + "VALUES (1004, 'Madan Kesh', '4th Street, Lane 3, DELHI', 'quality insurance mamager') "; executeSql(sql); } public static void Main(String[] argv) { string databaseName = "riskDatabase"; string currDatabasePath = "E:\liveProgrammes\cSharpWorkplace\riskWizard\A pp_Data"; // Need to be more flexible. string database_mdf = "'E:\liveProgrammes\cSharpWorkplace\riskWizard\ App_Data\riskDatabase.mdf'"; string database_ldf = "'E:\liveProgrammes\cSharpWorkplace\riskWizard\ App_Data\riskDatabase.ldf'"; RiskWizard riskWizard = new RiskWizard(databaseName, currDatabasePath, database_mdf, database_ldf); riskWizard.createDatabase(); riskWizard.createTable("userTable"); riskWizard.insertData("userTable"); //riskWizard.dropDatabase(); } } }
View Replies !
For Deletion..trigger Is Not Working
Hi, I have this trigger, it is working fine when i add new data but it doesn't work when I delete data from the table? Any idea? Any help will be highly appreciated. CREATE TRIGGER [PROP_AMT] ON [dbo].[cqe_item] FOR INSERT, UPDATE, DELETE AS DECLARE @var_DB_contract INTEGER, @var_CQE INTEGER, @var_PC INTEGER, @var_item VARCHAR(7), @var_AMT_PAID INTEGER, @var_AMT_RET INTEGER, @var_ITEM_NEW VARCHAR(1), @var_quant DECIMAL, @var_fiyr INTEGER, @var_amt_result INTEGER, @var_amt_ret_result INTEGER, @var_amt_old INTEGER, @var_amt_ret_old INTEGER, @var_quant_result INTEGER, @var_quant_new INTEGER, @var_quant_old INTEGER, @Item_new VARCHAR(7), @var_chk varchar(1) --If Exists (Select 1 From Inserted) And Exists (Select 1 From Deleted) set @var_db_contract =(SELECT a.db_contract FROM inserted a,deleted b where a.db_contract = b.db_Contract and a.cqe_numb = b.cqe_numb and a.pc_code = b.pc_code and a.item_no = b.item_no ) IF @var_db_contract IS NOT NULL BEGIN SET @var_db_contract=(SELECT a.db_contract FROM inserted a,deleted b where a.db_contract = b.db_Contract and a.cqe_numb = b.cqe_numb and a.pc_code = b.pc_code and a.item_no = b.item_no ) SET @var_cqe=(SELECT a.cqe_numb FROM inserted a,deleted b where a.db_contract = b.db_Contract and a.cqe_numb = b.cqe_numb and a.pc_code = b.pc_code and a.item_no = b.item_no ) SET @var_pc=(SELECT a.pc_code FROM inserted a,deleted b where a.db_contract = b.db_Contract and a.cqe_numb = b.cqe_numb and a.pc_code = b.pc_code and a.item_no = b.item_no ) SET @var_item=(SELECT a.item_no FROM inserted a,deleted b where a.db_contract = b.db_Contract and a.cqe_numb = b.cqe_numb and a.pc_code = b.pc_code and a.item_no = b.item_no ) SET @var_fiyr=(SELECT a.fy_item FROM inserted a,deleted b where a.db_contract = b.db_Contract and a.cqe_numb = b.cqe_numb and a.pc_code = b.pc_code and a.item_no = b.item_no ) set @var_chk ="Y" END ELSE BEGIN SET @var_db_contract=(SELECT a.db_contract FROM inserted a,deleted b where a.db_contract = b.db_Contract and a.cqe_numb = b.cqe_numb and a.pc_code = b.pc_code and a.item_no = b.item_no ) SET @var_cqe=(SELECT a.cqe_numb FROM inserted a,deleted b where a.db_contract = b.db_Contract and a.cqe_numb = b.cqe_numb and a.pc_code = b.pc_code and a.item_no = b.item_no ) SET @var_pc=(SELECT a.pc_code FROM inserted a,deleted b where a.db_contract = b.db_Contract and a.cqe_numb = b.cqe_numb and a.pc_code = b.pc_code and a.item_no = b.item_no ) SET @var_item=(SELECT a.item_no FROM inserted a,deleted b where a.db_contract = b.db_Contract and a.cqe_numb = b.cqe_numb and a.pc_code = b.pc_code and a.item_no = b.item_no ) SET @var_fiyr=(SELECT b.fy_item FROM inserted a,deleted b where a.db_contract = b.db_Contract and a.cqe_numb = b.cqe_numb and a.pc_code = b.pc_code and a.item_no = b.item_no ) set @var_chk="N" END SET @var_amt_paid=(SELECT a.amt_paid_item FROM inserted a,deleted b where a.db_contract = b.db_Contract and a.cqe_numb = b.cqe_numb and a.pc_code = b.pc_code and a.item_no = b.item_no ) SET @var_amt_old=(SELECT b.amt_paid_item FROM inserted a,deleted b where a.db_contract = b.db_Contract and a.cqe_numb = b.cqe_numb and a.pc_code = b.pc_code and a.item_no = b.item_no ) SET @var_amt_result =ISNULL(@var_amt_paid,0) - ISNULL(@var_amt_old,0) SET @var_amt_ret = (SELECT a.amt_ret_item from inserted a,deleted b where a.db_contract = b.db_Contract and a.cqe_numb = b.cqe_numb and a.pc_code = b.pc_code and a.item_no = b.item_no) SET @var_amt_ret_old=(SELECT b.amt_ret_item from inserted a,deleted b where a.db_contract = b.db_Contract and a.cqe_numb = b.cqe_numb and a.pc_code = b.pc_code and a.item_no = b.item_no) SET @var_amt_ret_result = isnull(@var_amt_ret,0) - isnull(@var_amt_ret_old,0) SET @var_quant_new = (SELECT a.quantity from inserted a,deleted b where a.db_contract = b.db_Contract and a.cqe_numb = b.cqe_numb and a.pc_code = b.pc_code and a.item_no = b.item_no) SET @var_quant_old =(SELECT b.quantity from inserted a,deleted b where a.db_contract = b.db_Contract and a.cqe_numb = b.cqe_numb and a.pc_code = b.pc_code and a.item_no = b.item_no) SET @var_quant_result = isnull(@var_quant_new,0) - isnull(@var_quant_old,0) SELECT @item_new = new_item FROM VALID_ITEM WHERE DB_CONTRACT = @var_db_contract AND PC_CODE = @var_PC AND ITEM_NO = @var_ITEM UPDATE ae_contract set amt_paid_contr = isnull(amt_paid_contr,0) +@var_amt_result, amt_ret_contr = isnull(amt_ret_contr,0) + @var_amt_ret_result where db_contract = @var_db_contract IF @item_new = 'N' BEGIN update vendor set used_amt = isnull(used_amt,0) + @var_amt_result + @var_amt_ret_result where db_vendor = (select gen_contr from ae_contract where ae_contract.db_contract=@var_db_contract); END UPDATE enc_det set amt_paid_fy = isnull(amt_paid_fy,0) + @var_amt_result, amt_ret_fy = isnull(amt_ret_fy,0) + @var_amt_ret_result where db_contract = @var_db_contract and pc_code = @var_pc and fy = @var_fiyr UPDATE valid_item set tamt_ret_item = isnull(tamt_ret_item,0) + @var_amt_ret_result, tamt_paid_item = isnull(tamt_paid_item,0) + @var_amt_result, qtd = isnull(qtd,0) + @var_quant_result where db_contract = @var_db_contract and pc_code = @var_pc and item_no = @var_item
View Replies !
Deletion Of Duplicate Values
hi, i am trying to delete rows where a particular column (hours) has the same value for the same member (primary key) but where the effective dates are different. i want to delete the duplicate(s) rows which have the most recent effective date(s). can you help?
View Replies !
How To Compare Data Before Deletion
SET identity_insert dbo.table1 on GO insert into dbo.table1( PrimaryKeyCol,Col1, Col2 .....) select PrimaryKeyCol,Col1, Col2...... from [Sever].Database.dbo.table1 as ClientColumn where not exists( select * from dbo.table1 as ServerColumn where ServerColumn.PrimaryKeyCol = ClientColumn.PrimaryKeyCol ) DELETE FROM [Server].Database.dbo.table1 where exists( where ServerColumn.PrimaryKeyCol = ClientColumn.PrimaryKeyCol ) SET identity_insert dbo.table1 off GO I can't complie this code.. anybody see where I went wrong?? Thanks for all your help.
View Replies !
Table Deletion Error
hi i am using sql server 2005 express edition , with asp.net i am trying to delete a table programmatically a button on a form , if the client clicked it , then a table should be dropped . but always i get an error message , that says "cannot drop table <table name> , becaust it does not exist or you do not have premissions to do that" could any body help plz thax ghassan
View Replies !
Deletion Problem In Sql Table
i am using this statement for deleting a single row in sql table. "DELETE FROM Random WHERE NewID= '" & strwinner & "'" where "strwinner" is the variable which contains the row to be deleted. the problem is that when i check the table in sql the row which was supposed to be deleted is sitll there.it does not give me any error statement or something. iam executing this statement by using ExecuteNonQuery in my .aspx page. please help
View Replies !
SQL Server Query, Are You Able To Bunch Together Child Table Fields.
Hi all, I'm using SQL Server 2005 along side Visual Studio 2005, using VB to create a web application at work. Now I'd like to bunch together some child fields in a gridview when displayed. Have a look at the attached pic to show what I would like. Is this possible via a query or would I need to set something up on the gridview to do this? Cheers, Paul.
View Replies !
Deletion Old Data In Replication Environment
Hi to allI have a question about deletion of amount of data:My production environment is this one:- one publisher with a database (historycal events)- 50 subscribers with the prev database in unidirectional replicationunidirectional (from subscribers to publisher)My target was capturing events from the subscribers to send them topublisher (later I can do reports on it).Once the data is on the server i don't need them any more in subscribers.Now I would like to delete the oldest data (year 2003) of some table on thepublisher (remember that replication is unidirectional S->P).The tables contain about 6-7 millions of records.I delete one month per time. The process is about 30 minutes long and themerge agent subscribers changes in retry state.Can I use these queries to make faster this process? Eventually what kind ofproblems can I have ?DELETE FROM mydb WITH (PAGLOCK) WHERE mydb.dbo.mydate Between date1 anddate2orDELETE FROM mydb WITH (ROWLOCK) WHERE mydb.dbo.mydate Between date1 anddate2Thank you very much for your support.Marco
View Replies !
Rows Deletion Affected By Cursor
Hello, I am using a cursor to navigate on data...of a table.... inside the while @@fetch_status = 0 command I want to delete some rows from the table(temporary table) in order to not be processed... The problem is that I want this deletion to affect the rows the cursor has. I declared a dynamic cursor but it does not work. Does anyone know how I can do this?? Thanks :)
View Replies !
Retrival And Deletion Of Duplicate Rows.
I have a table...say tb1 of 20 columns which has 2.7 million rows. There is no PK and the only way of identifying a unique row can be done with combination of column1+column2+column3. Can anyone help me how to idetify the duplicate rows and also delete the duplicate rows. And to commit after every 5000 rows. ITS VERY URGENT....Thanks in advance.
View Replies !
SSIS Crash On Breakpoint Deletion
I'm having an issue with trying to delete breakpoints in my SSIS package. I think the breakpoints were created when I added dataviewers through my process, however the breakpoints were not deleted when I removed the dataviewers. It would then appear that my process would not halt on ANY breakpoints - orphaned or valid. Furthermore, whenever I tried deleting the breakpoints manually, my whole IDE would crash. I got around the issue by closing the dtsx page first, then deleting the breakpoints, and reopening my dtsx. Are these valid bugs with SSIS? Has anyone else experienced this? I'm running this against a SQL Server 2005 database using VStudio 2005 as an IDE. Thanks! Chris P
View Replies !
|