My SQL Is Not Working!!! My Hair Is Gone Is The Topic - FK Creation Not Being Called And More
Aug 1, 2006
I have 2 problems:
1) When I run this, etch time I keep getting the error saying that constraint isn't found when I try to drop because my creation of the constraint at the end for some reason isn't creating it or being run
2) The first insert doesn't insert anything, although I get no errors
ALTER PROCEDURE Categories_I
3) I also get this when trying to run just the first 2 insert statements together
Msg 2627, Level 14, State 1, Line 7
Violation of PRIMARY KEY constraint 'Category_PK'. Cannot insert duplicate key in object 'Category'
ALTER PROCEDURE [domainnamemyaccountname].[Categories_I]
AS
BEGIN
/* delete contents from Category table and reseed
Cannot use truncate on a table which contains constraints therefore
use DBCC to reset the seed and DELETE to clear the records
*/
ALTER TABLE dbo.Category DROP CONSTRAINT Category_Category_FK1
PRINT 'Dropped FK'
SET IDENTITY_INSERT Category ON
INSERT INTO dbo.Category
(CategoryId, ParentCategoryID, [Name], [Description], DisplayOrder, DisplayInExplorer, Keywords, Active, CreateDate, CreateUserID)
SELECT 1, 1, CategoryName, '', 1, 1, '', 1, GETDATE(), 1 FROM CategoriesStaging WHERE CategoryName = 'All'
PRINT 'Inserted All Record'
INSERT INTO dbo.Category
(CategoryID, ParentCategoryID, [Name], [Description], DisplayOrder, DisplayInExplorer, Keywords, Active, CreateDate, CreateUserID)
SELECT 2, 1, CategoryName, '', 1, 1, '', 1, GETDATE(), 1 FROM CategoriesStaging WHERE CategoryName = 'Store'
PRINT 'Inserted Store Record'
SET IDENTITY_INSERT Category OFF
/* Finally, insert the rest and match on the Parent
Category Name based on the CategoryStaging table
*/
WHILE (@@ROWCOUNT <> 0)
BEGIN
INSERT INTO dbo.Category
(ParentCategoryID, [Name], [Description], DisplayOrder, DisplayInExplorer, Keywords, Active, CreateDate, CreateUserID, UpdateDate, UpdateUserID)
SELECT c.CategoryID, s.CategoryName, '', 1, 1, '', 1, GETDATE(), 1, GETDATE(), 1
FROM Category c INNER JOIN CategoriesStaging s ON c.[Name] = s.ParentCategoryName
WHERE NOT EXISTS (SELECT 1 FROM Category c WHERE s.[CategoryName] = c.[Name])
END
PRINT 'Inserted Rest of Category Records'
PRINT 're-create FK Call'
ALTER TABLE dbo.Category
ADD CONSTRAINT Category_Category_FK1 FOREIGN KEY
(
ParentCategoryID
) REFERENCES Category (
CategoryID
)
PRINT 'create FK2'
END
Other errors:
(1 row(s) affected)
Checking identity information: current identity value '2', current column value '0'.
DBCC execution completed. If DBCC printed error messages, contact your system administrator.
Msg 3728, Level 16, State 1, Line 6
'Category_Category_FK1' is not a constraint.
Msg 3727, Level 16, State 0, Line 6
Could not drop constraint. See previous errors.
ALTER TABLE statement conflicted with COLUMN FOREIGN KEY SAME TABLE constraint 'Category_Category_FK1'. The conflict occurred in database 'Chefs2', table 'Category', column 'CategoryID'.
In a stored procedure the following code snippet 1 checks against duplicate data being inserted. I've tested it with snippet 2 and it works as expected. However, when the procedure is called from ASP.NET the check seems ineffective. I still get the error msg. The application uses a SqlDataSource with the following parameters.
Any suggestions?
Thanks,
Bakis.
PS I want to ask a question on the ASP.NET forum .The login/pwd for this forum "get me in" to the .net forum in the sense that when I log in I see a logout link. I don't get an "ask a question" button though. Is there a separate screening for each forum?
<UpdateParameters>
<asp:Parameter Name="CatItemUID" Type="Int32" />
<asp:Parameter Name="CatName" Type="String" />
<asp:Parameter Name="Item" Type="String" />
<asp:Parameter Name="Quad" Type="Int16" />
<asp:Parameter Name="UID" Type="Int64" />
</UpdateParameters>
snippet 1 :
if (@CatItemComboExists > 0 ) BEGIN --print @CatItemComboExists return 0 END
snippet 2:
begin tran declare @return_status int EXECUTE @return_status = spUpdateCatItemRec 343, 'blah','blih', 2,3 print @return_status rollback
error msg only if proc is called from app
Violation of UNIQUE KEY constraint 'IX_tblCatItemUID'. Cannot insert duplicate key in object 'tblCatItemUID'.
OK, I have been raking my brains with this and no solution yet. I simply want to update a field in a table given the record Id. When I try the SQL in standalone (no sp) it works and the field gets updated. When I do it by executing the stored procedure from a query window in the Express 2005 manager it works well too. When I use the stored procedure from C# then it does not work: 1. ExecuteNonQuery() always returns -1 2. When retrieving the @RETURN_VALUE parameter I get -2, meaning that the SP did not find a matching record. So, with #1 there is definitely something wrong as I would expect ExecuteNonQuery to return something meaningful and with #2 definitely strange as I am able to execute the same SQL code with those parameters from the manager and get the expected results. Here is my code (some parts left out for brevity):1 int result = 0; 2 if (!String.IsNullOrEmpty(icaoCode)) 3 { 4 icaoCode = icaoCode.Trim().ToUpper(); 5 try 6 { 7 SqlCommand cmd = new SqlCommand(storedProcedureName);(StoredProcedure.ChangeAirportName); 8 cmd.Parameters.Add("@Icao", SqlDbType.Char, 4).Value = newName; 9 cmd.Parameters.Add("@AirportName", SqlDbType.NVarChar, 50).Value = (String.IsNullOrEmpty(newName) ? null : newName); 10 cmd.Parameters.Add("@RETURN_VALUE", SqlDbType.Int).Direction = ParameterDirection.ReturnValue; 11 cmd.Connection = mConnection; // connection has been opened already, not shown here 12 cmd.CommandType = CommandType.StoredProcedure; 13 int retval = cmd.ExecuteNonQuery(); // returns -1 somehow even when RETURN n is != -1 14 result = (int)cmd.Parameters["@RETURN_VALUE"].Value; 15 16 } 17 catch (Exception ex) 18 { 19 result = -1; 20 } 21 }
And this is the stored procedure invoked by the code above:1 ALTER PROCEDURE [dbo].[ChangeAirfieldName] 2 -- Add the parameters for the stored procedure here 3 @Id bigint = null,-- Airport Id, OR 4 @Icao char(4) = null,-- ICAO code 5 @AirportName nvarchar(50) 6 AS 7 BEGIN 8 -- SET NOCOUNT ON added to prevent extra result sets from 9 -- interfering with SELECT statements. 10 SET NOCOUNT ON; 11 12 -- Parameter checking 13 IF @Id IS NULL AND @Icao IS NULL 14 BEGIN 15 RETURN -1;-- Did not specify which record to change 16 END 17 -- Get Id if not known given the ICAO code 18 IF @Id IS NULL 19 BEGIN 20 SET @Id = (SELECT [Id] FROM [dbo].[Airports] WHERE [Icao] = @Icao); 21 --PRINT @id 22 IF @Id IS NULL 23 BEGIN 24 RETURN -2;-- No airport found with that ICAO Id 25 END 26 END 27 -- Update record 28 UPDATE [dbo].[Airfields] SET [Name] = @AirportName WHERE [Id] = @Id; 29 RETURN @@ROWCOUNT 30 END
As I said when I execute standalone UPDATE works fine, but when approaching it via C# it returns -2 (did not find Id).
Hi,I wanted to know how actually a database converter works.I am working on a converter from DBF to MS SQL server 2000using Visual Basic 6.0. I wanted to know that once a legacy databaseis enterd in the program, how does it get normalised.I have aboout 40 tables in DBASE IV format. I want to convert theminto relational database and store them on server. But on conversion,how can the converted data be normalised by itself.Awaiting the replies,Thanks
Ok so every week I have to download a file containing in excess of 40000 products. I then have to change the category ids to suit my system. Is there a script or something that I could create so I just run it each week to do a search and replace and then loop until all category ids have been changed.
Table = ecommstore Column = section
I would need to change say from 84 to 1 then 86 to 2, 87 to 3 etc etc
I was using access with visual studio express but issues and advice steered me to server express
However I cannot seem to pass the first hurdle
I have created a table and relevant dataset.
I have created a form to hold to view, update, insert and delete i.e. the form has a database strip at the top.
But when I try to add, update or delete records, the database does not reflect the changes.
I saw a forum that stated that changing the database property to "copy if newer", i did this but still no effect.
Is VB really this difficult. I thought with my experience of access and vba I would learn quickly but it seems that I have to take 4 steps back to take one forward.
My intention is ti build quite an indepth application that generates reports and some advanced stuff. But I am wondering if it is worth it as after three weeks I haven't been able to create an application that can communicate with a database then add, delete and update some info. At this rate I might be able to sum a set of records after a year.
I really am thinking of going to a php/mysql application. Is VB really worth it after three weeks of trawling the internet for help, not finding it, coming up with a new idea, trying to find info on the internet, not finding it and so on...
To make matters worse when I wrote this post earlier and tried to post it, something failed and I have had to type it again. Perhaps a higher being is steering me away.
Anyway I imagine people will probably ignore this as in early post but if someone knows what I am doing wrong then please help.
SQL Server 2000 - Backend Access 2000 Runtime - Front End Connecting via ODBC
I have read loads and loads of examples and looked at other sources of info for help on this but am struggleing big time.
I have multiple users working in the same database table. The problem is they often get an error message about the record has been changed and would they like to save the changes to clipboard etc etc.
I basicly want to implement pessimistic locking for my tables. So once a user has started to edit that record nobody else can get to it.
I am the only DBA for a company of about 200 employees which makes about 100 million a year; I have 8 SQL servers some with over 70 databases on them that feed our web sites and educational web sites. I also have a few databases that are between 75 and 120 Gig that is for our circulation system. I am the Systems admin for all of the systems that run of my SQL server, so that makes our circ system, tradeshow system, accounting system, web sites there are about 90 of them or so. I also do programming for our IT department and some web site stuff as well as for our tradeshow dept. I am the answer man for our sales people and programmers, I also have the knowledge to build by own servers and run a network. So that€™s over 200 databases plus all the other *** that I do. Oh and by the way I'm supposed to help out and cover for our Tec support guys, witch there are 2 of them by the way. I can never take any more than 3 days off at a time; I have a month€™s vacation. I do all this for under $55,000 a year. I am never included in any decisions on software that runs on SQL nor am I consulted on any thing having to do with SQL. I work for a director who knows nothing about SQL server. There are 2 JR data guys and they do just data queries and deal with the day to day circ requests. These guys both have an office not to mention the tech guys have an office and guess what I am in a cube. I asked my boss for a laptop with a Verizon air card so when I€™m not at work if something happens that needs my attention I do have to drive to work or go home and remote in, here is the best part he looked at me and asked if I was high. I am on call 24/7 365. I have over 10 years experience working with SQL. I€™m I crazy for staying? I have been with this company for almost 8 years; I am the one who started them out on SQL server. I have converted every thing over to SQL 98.5% of all the company data I am in charge of. What would you do?
The machine originally had SQL express successfully installed but had been removed moths ago.
After trying to re-install I'm getting SQL won't start, but it can't the installation isn't there. I go to microsoft sql server folder, both folders 80 and 90 are there but no MSSQL folder
Here is the code, if somebody is interested about it. It is oracle, not SQL server, but the idea is the same.
drop view a; drop view b; drop view figure5_9;
create view a as select d.donorID, dt.donortype, dt.donortargetq1 from donortype dt, donor d where d.donortype=dt.donortype;
select * from a;
create view b as select a.donortype, sum(c.ContributionAmount) as amount from Contribution c, a where c.ContributionDate between '01-JAN-06' and '31-MAR-06' and a.donorID=c.donorID group by a.donortype;
select * from b;
create view figure5_9 as select b.donortype, a.donortargetq1, b.amount, b.amount/a.donortargetq1 as percentage from a, b where a.donortype=b.donortype group by b.donortype, a.donortargetq1, b.amount;
I am trying to extract data from a MySQL DB. I have installed the MySQL Connector (mysql-connector-odbc-3.51.23-win32), then set up an ODBC connector in the Control Panel > ODBC.
Then in BIDS I have setup a new ODBC connection in Connection Managers, and then used the ODBC connection I setup above so at that point everything looks cool.
Now what? Do I setup a Execute SQL Task or how do I get the data out and into a Data Flow Task?
Hi all - I receive the error below at the end of one of my DTS packages. All steps in the package actually complete successfully but right at the end I get a Microsoft Visual C++ Debug Library pop-up with the following:
I'm in China doing TechEds in Shanghai, Guangzhou, Beijing and Hong Kong - returning to the office Monday 2nd October.
There may be significant delays in my replies to any topics on this forum. Just fyi so you don't sit waiting for me to respond.
Thanks
Paul Randal Lead Program Manager, Microsoft SQL Server Core Storage Engine (Legalese: This posting is provided "AS IS" with no warranties, and confers no rights.)
It's been pretty quiet here recently - hopefully people either aren't experiencing corruptions or they're finding what they need in the previous threads.
Just a quick note to say that I'll be totally offline from tomorrow until January - going diving in Indonesia (http://www.wakatobi.com).
Happy holidays and may your pagers be silent throughout
Cheers
Paul Randal Principal Lead Program Manager, Microsoft SQL Server Core Storage Engine (Legalese: This posting is provided "AS IS" with no warranties, and confers no rights.) http://blogs.msdn.com/sqlserverstorageengine/default.aspx
I'm thinking of doing some basic parsing of address. I want to seprateout the house number from the street name from the suffix. I have thesuffix's from the USPS, but I cant find a database of US street names.Anyone come across one or know where I can get one?TIARob/end off topic
Hello. I see a lot of threads re this but I havent seem an answer. Please help. I have Win xp pro SP2 with msde, IIS 5.1 and Web Data Administrator on two separate machines.
With one machine everything works great. On the other, When I hit the Web Data Administrator Login button (windows integrated or SQL) it just shows the hour glass and doesnt do anything.
On the one that works, I can change the server to one on our lan with sqlserver and it will link in fine. However with the other, the same hourglass shows.
IIS and msde are both running and seem to work fine. I can browse to localhost virtual directories (I have dotnetnuke running using msde on localhost) and access the database from dotnetnuke and visual studios.
I have made sure my localhost is a "Trusted site" und ie browser and I have enable windows integrated authentication for the default web site and the webadmin virtual directory.
I have a field which stores date which the datetime datatype... The problem is that I am also getting time information in this stored field.
I just want to extract the date part in dd-Mmm-yy format (e.g. 07-May-04). I tried convert (char (8), MyDateField, 112) but it gives me date in yyyymmdd format. How do I get the results in dd-Mmm-yy format instead?
I'm not at all comfortable with SSIS so please forgive me if I overload you all with information here:
I need to create a data table using SSIS which does not delete the previous days data. So far all the data tables we use to write reports in Visual Studio are constructed in SSIS as follows.
1 - Excecute SQL Task - DELETE FROM STOCK 2 - Data Flow Task 3 - Data Reader Source - SELECT * FROM ODBCDATASOURCE 4 - OLE DB Destination (Creates table STOCK)
The data tables which are created this way are stored in a data warehouse and scheduled to refresh once a day, which means that any data from yesterday is lost when the updates run. So, I tried to create a table which never has its previous days' data deleted by using just the last three steps above - and it worked great in Visual Studio, no problem at all. However, when I added this SSIS Package to the Update Job in SQL Server Management Studio, the job totally rejected the packed with the message: "The command line parameters are invalid. The step failed".
I thought I could work around this problem by asking the job step to excecute a simple SQL query to insert the data from table1 into table2 (and would thus negate the need for a SSIS Packege at all), but it threw me a curve ball with some message about not being able to use proxy accounts to run T-SQL Scripts.
If anyone knows how to create a SSIS package in which the data never expires please could you impart some wisdom my way. I only need to do this once for a specific report.
Please, when answering, bear in mind that I'm a simple fellow with little understanding of the inner workings of SQL Server and its various components, so please use short sentences and simple words.
We have an SSAS instance where when we run the query "select * from $system.discover_traces" the creation time in the resultset shows a different time from when we actually started the trace.
for example if we have create the trace at 3.30pm it shows 7.35 pm in the Sql server management studio resultset when we run the query "select * from $system.discover_traces".
How can I execute or access a web page from a DTS package?
Both SQL server AND website are hosted on the same server (a Dual 2.4Gz Xeon with 2Gb RAM, RAID 5 etc)
I have 2 tables in SQL server 2000 that hold orders. These need to be posted into another table at a predefined time (ie: 4:30pm) and at the same time, access a remote address (a web service) and post certain elements of the order back.
Basically, can anyone help me out on how to execute a web page from a DTS.
I do NOT want to access a DTS from a webpage, which is all I'm finding at the moment.
Hello, Question is, when I try to create relationships in SQL 7 without using the wizard..upon adding the tables I get an errror message that says "Coinitialization has not been called". What does this mean?
I'm stumped on what to cal this, there might even be a method or pattern named for what i am trying to accomplish...
In the database, a number field is included on each table
When the DAL reads the record from the database, it is passed to the client - work is possibly done to the record and is sent back to the DAL for update.
A query is done against the table to retrieve the record again, the numbers are compared - if they don't match, it is assumed the record been modified by another user/thread/activity. An error is returned to the client stating the data has been changed.
if the numbers match, the record is updated with the number field being incremented by one.
what is this methodology called (beside crap :-) )
Hello, perhaps you guys have heard this before in the past, but here iswhat I'm looking for.I have a SQL 2000 table with Social security numbers. We need tocreate a Member ID using the Member's real SSN but since we are notallowed to use the exact SSN, we need to add 1 to each number in theSSN. That way, the new SSN would be the new Member ID.For example:if the real SSN is: 340-53-7098 the MemberID would be 451-64-8109.Sounds simply enough, but I can't seem to get it straight.I need this number to be created using a query, as this query is areport's record source.Again, any help would be appreciated it.
This seems like a basic question but I have not been able to find the answer in the help files or by searching this forum.
Is a trigger called for each row updated or is it called once for all rows updated?
for example if I have:
Code Snippet CREATE TRIGGER mytrigger
ON mytable AFTER UPDATE AS BEGIN
EXEC e-mail-me inserted, N'mytrigger', getdate() END
and I do this
Code Snippet UPDATE mytable SET mycolumn = N'whatever' WHERE ID > 5 AND ID <= 10
Assuming there is a record for each nteger value of ID, than will mytrigger run 5 times (once for each row updated) or one time (with inserted containing all 5 rows)?
When a column is evaluated against an UDF in a SELECT ... or WHERE ... It makes sense that the UDF is called for every row of the SELECT. But is it still true if the UDF is called in a subquery as below?
Code Snippet
SELECT LineID, AnyText FROM dbo.UdfTest WHERE LineID IN (SELECT LineID FROM dbo.F_Bogus()) I've made a test and the SQL Profiler Trace shows that the UDF is called only once.
Can anyone confirm if my test is valid and most importantly that the UDF is called only once? FYI, I never use sub queries. This is to clarify a technical detail for our performance investigation.
Thank in advance for any help.
Here is the code to setup the test: USE NorthWind GO
CREATE TABLE dbo.UdfTest ( LineID int Identity(1,1) NOT NULL, AnyText varchar(200) COLLATE database_default NOT NULL ) GO
CREATE FUNCTION dbo.F_Bogus ( ) RETURNS @tab TABLE ( LineID int NOT NULL, AnyText varchar(100) COLLATE database_default NOT NULL) AS BEGIN INSERT @tab (LineID, AnyText) VALUES (1, 'UDF1') INSERT @tab (LineID, AnyText) VALUES (2, 'UDF2') INSERT @tab (LineID, AnyText) VALUES (3, 'UDF3') INSERT @tab (LineID, AnyText) VALUES (4, 'UDF4') INSERT @tab (LineID, AnyText) VALUES (5, 'UDF4')
RETURN END GO
Here is the capture of SQL Profiler when executing the statement: SELECT LineID, AnyText FROM dbo.UdfTest WHERE LineID IN (SELECT LineID FROM dbo.F_Bogus())
SQL:BatchStarting SELECT LineID, AnyText FROM dbo.UdfTest WHERE LineID IN (SELECT LineID FROM dbo.F_Bogus()) 51 2008-05-06 17:58:31.543 SQLtmtStarting SELECT LineID, AnyText FROM dbo.UdfTest WHERE LineID IN (SELECT LineID FROM dbo.F_Bogus()) 51 2008-05-06 17:58:31.543 SPtarting SELECT LineID, AnyText FROM dbo.UdfTest WHERE LineID IN (SELECT LineID FROM dbo.F_Bogus()) 51 2008-05-06 17:58:31.577 SPtmtCompleted -- F_Bogus INSERT @tab (LineID, AnyText) VALUES (1, 'UDF1') 51 2008-05-06 17:58:31.577 SPtmtCompleted -- F_Bogus INSERT @tab (LineID, AnyText) VALUES (2, 'UDF2') 51 2008-05-06 17:58:31.577 SPtmtCompleted -- F_Bogus INSERT @tab (LineID, AnyText) VALUES (3, 'UDF3') 51 2008-05-06 17:58:31.577 SPtmtCompleted -- F_Bogus INSERT @tab (LineID, AnyText) VALUES (4, 'UDF4') 51 2008-05-06 17:58:31.577 SPtmtCompleted -- F_Bogus INSERT @tab (LineID, AnyText) VALUES (5, 'UDF4') 51 2008-05-06 17:58:31.577 SPtmtCompleted -- F_Bogus RETURN 51 2008-05-06 17:58:31.577 SQLtmtCompleted SELECT LineID, AnyText FROM dbo.UdfTest WHERE LineID IN (SELECT LineID FROM dbo.F_Bogus()) 51 2008-05-06 17:58:31.543 SQL:BatchCompleted SELECT LineID, AnyText FROM dbo.UdfTest WHERE LineID IN (SELECT LineID FROM dbo.F_Bogus()) 51 2008-05-06 17:58:31.543
I have some nightly jobs that execute stored procedure to call the tables? I want to know which table are called by these stored procedures. Is it possible? Any idea will be appreciated.