Is There A Command That Returns Every Constraint Related To A Colonne/table
May 14, 2008
Hi,
Not too long ago I was looking to change a primary key in a table from one column to another, the standard accepted procedure to so procedure to do so (I was told) was:
1) drop primary key constraint from old_key_column
2)add primary key constraint to new_key_column
3) drop old_key_column (optional).
In order to carry out the first step, I needed the name of the primary key constraint, at which point I asked around for a command that would return that name (and would quite probably take as a parameter the name of the column that key is related to). The answer was :
Try this:
select name 'constraintName' from sys.indexes where object_id=object_id('<tableName>') and is_primary_key=1
Unfortunately this command never worked for me. Probably because I don't have a table sys.indexes in my DB, but I can see a table sysindexes in the system tables folder, then again that table doesn't have an object_id column, but it has an id column, finally this column only contain obscur numbers.
So I am asking you all (again) for help, do you know about a command that returns every single constraint related to a column (or a table, or both).
One more thing, I am running SQL SERVER 2000, I do know that there are graphic ways to do those very operations (in the enterprise manager or the query analyzer) and I do know those ways (that's how i got past the problem mentioned earlier), I just think that knowing how to do it programmatically would be a plus.
PS: I am a total newbie to T-SQL (and a still a beginner in SQL, so please take it easy with me )
OK heres the situation, I have a Categories table and a Products table, each Category can have one or many Products, but a product can only belong to one Category hence one-to-many relationship.
Now I want to do a SELECT query that outputs all of the Categories onto an ASP page, but also displays how many Products are in each category eg.
CatID | Name | Description | No. Products
0001 | Cars | Blah blah blah | 5
etc etc
At the moment I'm doing nesting in my application logic so that for each category that is displayed, another query is run that returns the number of products for that particular category. It works ok!
However, is there a way to write a SQL Statement that returns all the Categories AND number products from just the one SELECT statement, rather than with the method I'm using outlined above? The reason I'm asking is that I want to be able to order by the number of products for each category and my method doesn't allow me to do this.
--Table 1 "Employee" CREATE TABLE [MyCompany].[Employee]( [EmployeeGID] [int] IDENTITY(1,1) NOT NULL, [BranchFID] [int] NOT NULL, [FirstName] [varchar](50) NOT NULL, [MiddleName] [varchar](50) NOT NULL, [LastName] [varchar](50) NOT NULL, CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED ( [EmployeeGID] ) GO ALTER TABLE [MyCompany].[Employee] WITH CHECK ADD CONSTRAINT [FK_Employee_BranchFID] FOREIGN KEY([BranchFID]) REFERENCES [myCompany].[Branch] ([BranchGID]) GO ALTER TABLE [MyCompany].[Employee] CHECK CONSTRAINT [FK_Employee_BranchFID]
-- Table 2 "Branch" CREATE TABLE [Mycompany].[Branch]( [BranchGID] [int] IDENTITY(1,1) NOT NULL, [BranchName] [varchar](50) NOT NULL, [City] [varchar](50) NOT NULL, [ManagerFID] [int] NOT NULL, CONSTRAINT [PK_Branch] PRIMARY KEY CLUSTERED ( [BranchGID] ) GO ALTER TABLE [MyCompany].[Branch] WITH CHECK ADD CONSTRAINT [FK_Branch_ManagerFID] FOREIGN KEY([ManagerFID]) REFERENCES [MyCompany].[Employee] ([EmployeeGID]) GO ALTER TABLE [MyCompany].[Branch] CHECK CONSTRAINT [FK_Branch_ManagerFID]
--Foreign IDs = FID --generated IDs = GID Then I try a simple single row DELETE
DELETE FROM MyCompany.Employee WHERE EmployeeGID= 39
Well this might look like a very basic error: I get this Error after trying to delete something from Table €śEmployee€?
The DELETE statement conflicted with the REFERENCE constraint "FK_Branch_ManagerFID". The conflict occurred in database "MyDatabase", table "myCompany.Branch", column 'ManagerFID'.
Yes what I€™ve been doing is to deactivate the foreign key constraint, in both tables when performing these kinds of operations, same thing if I try to delete a €śBranch€? entry, basically each entry in €śbranch€? and €śEmployee€? is child of each other which makes things more complicated.
My question is, is there a simple way to overcome this obstacle without having to deactivate the foreign key constraints every time or a good way to prevent this from happening in the first place? Is this when I have to use €śON DELETE CASCADE€? or something?
Hi,I have an sqlCommand return the ID from the last inserted row. I use SELECT SCOPE_IDENTITY within the SQL.When I call the function it returns a Decimal instead of an integer??So I want to convert this to an integer, however this is not liked by the compiler since the overloaded method for the decimal conversion is obviously a decimal, but the ExecuteScalar parameter is of type object.iReturnVal = decimal.ToInt32(_sqlCommand.ExecuteScalar()); <--- compiler complains....So I changed to this:iReturnValue = decimal.ToInt32((decimal)_sqlCommand.ExecuteScalar());Can someone tell me if this is the right way to do it? Seems messy code to me...
could someone please tell me : am I supposed to use the OLE DB Command in a dataflow to call a stored procedure to return a value? Or is it just supposed to be used to call a straightforward insert statement only?
What I am hoping to do:
I have a table with a few columns and one identity column. In a dataflow I would like to effect an insert of a record to this table and retrieve the identity value of the inserted record... and I'd like to store the returned identity in a user variable.
If I AM supposed to be able to do this... then how on earth do I do it?
I have spent hours fooling around with the OLE DB command trying to call a stored proc and get a return value.
In the Advanced Editor any time I try to add an output column (by clicking on Add Column) I just get an error dialog that says "the component does not allow adding columns to this input or output)
So, am getting pretty concussed .. banging my head of the wall like this...
So put me out of my misery someone please.... is the OLE DB Command intended for this or not?
I need to delete records from a table (Table1) which has a foreign key column in a related table (Table2).
Table1 columns are: table1Id; Name. Table2 columns include Table2.table1Id which is the foreign key to Table1.
What is the syntax to delete records from Table1 using Table1.Name='some name' and remove any records in Table2 that have Table2.table1Id equal to Table1.table1Id?
PeopleID in People Table is the primarykey and foreign Key in PeopleCosts Table. PeopleID is an autonumber
The major fields in People Table are PeopleID | MajorVersion | SubVersion. I want to create a new copy of data for existing subversion (say from sub version 1 to 2) in the same table. when the new data is copied my PeopleID is getting incremented and how to copy the related data in the other table (PeopleCosts Table) with the new set of PeopleIDs..
I have the following tablestblUserdatausercode username firstname lastname5 peter peter smith11 john433 john doe15 simonsays Simon SmithtblEventsID postedbycode title eventtext createdate1 5 woodstock 'oldies' 12/12/20082 11 love parade 'dance all night 1/1/20083 11 spring break 'great party' 2/2/2006tblEventVisitorsusercode eventid5 15 311 111 211 3As you can see User John433 is going to 3 events.But I only want to select the one that has the first upcoming startdate bigger than now: getdate()Desired output would be:username firstname lastname eventid title eventtext eventdatepeter Peter Smith 1 woodstock 'oldies' 12/12/2008john433 john doe 2 love parade 'dance all night 1/1/2008simonsays Simon Smith NULL NULL NULL NULLHow can I make such a selection? (perhaps see this thread for similar info: http://forums.asp.net/t/1201266.aspx)Thanks!
I have two tables. In tblUsers is all userdata. In table tblMoreInfo is some info on a user (0-15 records).Now I want to select tblUsers.username and tblUsers.usercode and the matching top 1 row tblMoreInfo.schoolname (top 1 based on tblMoreInfo.createdate) IF IT EVENT EXISTS from tblMoreInfo. If no matching record exists I want the value NULL to be returned for the schoolname...In all cases tblUsers.username must be unique (and I cant use the distinct keyword as im already using the row_number() function.Any help?Thanks!
I have table 1 from which I select some values belonging to users.In table 2 I store tips a user might give: tipid, tiptitle, tiptext,tipcreatedateA user may give more than one tip.But now I want a query that selects the info of a SINGLE user and the LATEST tip he created, so resultset might look like:username lastname sex tiptitle tiptext tipcreatedateSo even though a user might have given more tips, only the latest will be retreived...and thus 1 row for a particular user is returned...How would I construct such a query? The problem is that I want to get exactly 1 row but more than 1 column from the table 2, so I think I cannot use the SQL Server "TOP" command...
Hi all, What I'm trying to do and having a lot of trouble with is pulling how one user is related to another user from my database. I'll explain...
I set up a table called relationships that looks like this:
ID type: int
RELID1 type: int, is the user id that initiated the relationship request.
RELID2 type: int, is the user id of the second person in the relationship.
Story type: varchar(255), quick blerb on how they are related.
Type type: int, a number 1-20 based on the relationship they have
Status type: int, 1 = confirmed by second person, 0 = not confirmed
What i'd like to have pulled is a list of the people that person (for example: 70) is related to. I am having the two following problems: 1. unqid of "70" could be in RELID1 or RELID2 as they could have initiated the request or been the second person. 2. I don't want to display them selves in their own relationship listing
Example Data: ID 1 2 3 4
RELID1 25 15 70 12
RELID2 54 70 13 8
Story Met on the east coast Met at walmart Met walking Met outside
Type 14 11 3 8
Status 1 1 1 1
Example Output: Again assuming the current user is "70", the sql should pull: 15, 13.. but i'd like to pull their names from another table called "Users" where "15" and "13" are the UnqID's in a column called "ID". So: 15 = Bob Smith 13 = Jane Doe
The following code works great that I got with the help on another form:
SELECT Relationship.RELID1 , Relationship.RELID2 , ReMembers.FirstName , ReMembers.LastName FROM Relationship INNER JOIN ReMembers ON ReMembers.AccountID = Relationship.RELID1 WHERE Relationship.RELID2 = 70 UNION ALL SELECT Relationship.RELID1 , Relationship.RELID2 , ReMembers.FirstName , ReMembers.LastName FROM Relationship INNER JOIN ReMembers ON ReMembers.AccountID = Relationship.RELID2 WHERE Relationship.RELID2 = 70
My question is: What is the best way to set this table up? I'm not committed to any any design as of right now, but want to be sure I set it up in the most efficient manner.
Here is my issue I am new to 2005 sql server, and am trying to take my old data which is exported to a txt file and import it to tables in sql. The older database is non relational, and I had made several exports for the way I want to build my tables. I built my packages fine and everything is working until I start building relationships. I remove my foreign key and the table with the primary key will get updated for the package again. I need to update the data daily into sql, and once in it will only be update from the package until the database is moved over.
It will run and update with a primary key until I add a foreign key to another database.
Here is my error when running the package when table 2 has a foreign key.
[Execute SQL Task] Error: Executing the query "TRUNCATE TABLE [consumer].[dbo].[Client] " failed with the following error: "Cannot truncate table 'consumer.dbo.Client' because it is being referenced by a FOREIGN KEY constraint.". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.
I have two tables. When my user completes an insert of data in table (1), I would like the second "related" table (2) to be automatically populated with defaults. Is this possible? My logical approach to this is: 1. Build a handler for the OnInsert event of the first table 2. In the handler, call the Insert Command on the SQLDataSource for the second table with the defaults specified in the DataSource. What I'm not sure how to do is Step 2 or whats the best way. How do I call the Insertcommand programmatically for a DataSource? Or, is there a better way such as some kind of traditional hardwired SQL insert statement like in classical ASP? Or is there a way to programmatically call a stored procedure and if so is the 3rd approach the best way?
How exactly would someone do this best? It seems this would be a rather common thing someone might need to do.
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?
Hi,I've got VS 05 web dev express installed and i'm trying the walkthroughs for login admin. I've succeeded and noticed the tables VS05 produces in the database ASPNETDB.MDF. I've created a new table "Customers" also with a UserID and also configured it as "UniqueIdentifyer" as VS05 has done in the table aspnet_users. The Customers table has two other fields: CustID (autoint) and CustomerName. Now i'm setting up a detailsview control that should insert a CustomerName but I also want it to insert the current logged in userID to the Customers.UserID field so that the aspnet_users and customers tables can be related. My question is how would my Sql insert statement look like to incorporate the parameter of the current logged in UserID and insert it into the Customers.UserID field?thanks.
Hey guys, I have created an asp.net page where users can select multiple items and then submit the form. I would like to return related items back. The catch is, I want to only return items that are related to all of the selected items. I've created a SQL Procedure that puts each of the inputted item's ItemId in to a temp table, I have a second table called RelatedItems which I use as my junction table that has ItemId, and ReleatedItemId, I then have my Item table that has the data I want to get to (I've excluded this because I have no trouble pulling out data once I have an ItemId) I can pull out all related ItemIds with a simple join, however I don't know where to start when it comes to pulling out only items related to all ItemIds in the @TempTable. Any help or suggestions would be great. Thanks, Matt
I have a query/report that I need to create that needs to look at the size of a company and based on that size apply different rules. I am sure that this is not the only query/report I'll need to do using this and I'm also not so sure that the size ranges won't be changed in the future. Given this, I'd like to store the size ranges in a lookup(global) table. That way, if the ranges ever change I can just alter them in that table and not in all of the queries/reports that use them. What I need to figure out is how to join the live table with the look up table.
Specifically, here is what I have. The look up table would be:
Code Block CREATE TABLE #gl_sizerange ( glsid int IDENTITY(1,1) NOT NULL, lowsize int, highsize int, sizecat varchar(10), milestone varchar(25), days int ) ON [PRIMARY] INSERT into #gl_sizerange VALUES(1, 24, 'Small', 'Approach', 14) INSERT into #gl_sizerange VALUES(1, 24, 'Small', 'Interview', 14) INSERT into #gl_sizerange VALUES(1, 24, 'Small', 'Demonstrate', 21) INSERT into #gl_sizerange VALUES(1, 24, 'Small', 'Negotiate', 14) INSERT into #gl_sizerange VALUES(1, 24, 'Small', 'Close', 7) INSERT into #gl_sizerange VALUES(25, 99, 'Medium', 'Approach', 14) INSERT into #gl_sizerange VALUES(25, 99, 'Medium', 'Interview', 21) INSERT into #gl_sizerange VALUES(25, 99, 'Medium', 'Demonstrate', 21) INSERT into #gl_sizerange VALUES(25, 99, 'Medium', 'Negotiate', 14) INSERT into #gl_sizerange VALUES(25, 99, 'Medium', 'Close', 7) INSERT into #gl_sizerange VALUES(100, 499, 'Large', 'Approach', 14) INSERT into #gl_sizerange VALUES(100, 499, 'Large', 'Interview', 21) INSERT into #gl_sizerange VALUES(100, 499, 'Large', 'Demonstrate', 21) INSERT into #gl_sizerange VALUES(100, 499, 'Large', 'Negotiate', 14) INSERT into #gl_sizerange VALUES(100, 499, 'Large', 'Close', 7) INSERT into #gl_sizerange VALUES(500, 300000000, 'Super', 'Approach', 28) INSERT into #gl_sizerange VALUES(500, 300000000, 'Super', 'Interview', 35) INSERT into #gl_sizerange VALUES(500, 300000000, 'Super', 'Demonstrate', 28) INSERT into #gl_sizerange VALUES(500, 300000000, 'Super', 'Negotiate', 35) INSERT into #gl_sizerange VALUES(500, 300000000, 'Super', 'Close', 35)
Then what I have is two more tables, one that indicates the size of the company and another that has the milestone contained within it and I will also calculate how long that milestone has been open and if it is longer than what is in the lookup table for that milestone and size range I need it returned in the report. Here are some quick sample table to represent that data (I've condensed the size and number of tables for the example):
Code Block CREATE TABLE #en_entity ( enid int NOT NULL, orgsize int, ) ON [PRIMARY]
INSERT into #en_entity VALUES(1, 5) INSERT into #en_entity VALUES(2, 18) INSERT into #en_entity VALUES(3, 24) INSERT into #en_entity VALUES(4, 25) INSERT into #en_entity VALUES(5, 47) INSERT into #en_entity VALUES(6, 101) INSERT into #en_entity VALUES(7, 499) INSERT into #en_entity VALUES(8, 500) INSERT into #en_entity VALUES(9, 10000) INSERT into #en_entity VALUES(10, 567890) CREATE TABLE #op_opportunity ( opid int NOT NULL, enid int NOT NULL, milestone varchar(25), daysopen int ) ON [PRIMARY] INSERT into #op_opportunity VALUES(1, 1, 'Approach', 5) INSERT into #op_opportunity VALUES(2, 2, 'Interview', 18) INSERT into #op_opportunity VALUES(3, 4, 'Negotiate', 24) INSERT into #op_opportunity VALUES(4, 7, 'Demonstrate', 25) INSERT into #op_opportunity VALUES(5, 7, 'Approach', 7) INSERT into #op_opportunity VALUES(6, 9, 'Close', 35) INSERT into #op_opportunity VALUES(7, 8, 'Close', 36)
So, given the sample data, I would expect the results to return me the following opids from the #op_opportunity table because they don't comply with what is in the look up table based on milestone, size and days open: 2,3,4,7
Hi everyone! I'm on my way to learn SSIS by myself and it's a little complicated! I'd like to ask you one thing:
I have two tables at my data source, one is "Clients" and the other one is ClientsAddress. That is, a client can have more than one address. Both tables are related by a one to many relationship and the tables description is:
CLIENTS CLIENTSADDRESS #PK_Client #PK_Client other fields.. #ID_address ... other fields
What i intend to do is to obtain one table with approximately 3 fields, each one for a possible client address; something like this: CLIENTS PK_Client ID_Address1 ID_Address2 ID_Address3
My question is what transformation can i use? an how ?
Thanks very much in advance!! Emilio Leyes Salta, Argentina
I want with PowerPivot to tell what stage is in progress for project. I looked at RElatedTable, LOOKUPVALUES, but I can't find a way to associate this to get working. I got however the one telling me which projects are Completed.
Hi. This is a SQL question. I am trying to wrap a stored procedure with a UDF so I can do selects against the result. The following doesn't work, but is it possible to do something like: Create Function test()returns @tmp table ( myfield int)asbegin insert into @tmp (field1) Exec dbo.MySprocWhichRequires3ParmsAndReturnsATable 5, 6, 10 output returnend Thanks
I am looking for a script, that returns all SPs, which related to a given table, incl. the access type.For example: the SPs SP_test1, SP_test2, SP_test3 are dependencies of MyTable
This should be the result: MyTable --> SP_test1: select --> SP test1: update --> SP_test1: drop --> SP test2: delete --> SP_test3: insert
There are a lot of scripts, who returns the related SPs.
HI all,In SQL Server, i have a function which will return a table. likecreate function fn_test (@t int) returns table asreturn (select * from table)now i want the function to retun the table based on some condition like belowcreate function fn_test(@t int) returns table asif @t = 1 return (select * from table1)else return (select * from table2)It is not working for me. Please give me your suggesstions. It's very urgent.Thank you in advance....
select sq.*, p.numero, p.nombre from paf p right outer join dbo.GetListOfSquaresForShippingLot(@lot) sq on sq.number = p.numero and sq.version = p.numero
The @lot parameter is declared at the top ( declare @lot int; set @lot = 1; ). GetListOfSquaresForShippingLot is a CLR TVF coded in C#. The TVF queries a XML field in the database and returns nodes as rows, and this is completed with information from a table.
If I run a query with the TVF only, it returns data; but if I try to join the TVF with a table, it returns empty, even when I'm expecting matches. I thought the problem was the data from the TVF was been streamed and that's why it could not be joined with the data from the table.
I tried to solve that problem by creating a T-SQL multiline TVF that is supposed to generate a temporary table. This didn't fix the problem.
What can I do? Does anybody know if I can force the TVF to render its data somewhere so the JOIN works? I was thinking a rowset function could help, but I just can't figure out how.
PLEASE HELP!!!!
Let me know if you want the code for the CLR TVF. This is the code for the T-SQL TVF:
CREATE FUNCTION [dbo].[GetTabListOfSquaresForShippingLot] ( @ShippingLot int ) RETURNS @result TABLE ( Number int, Version int, Position smallint, SubModel smallint, Quantity smallint, SquareId nvarchar(5), ParentSquareId nvarchar(5), IsSash smallint, IsGlazingBead smallint, Width float, Height float, GlassNumber smallint, GlassWidth float, GlassHeight float ) AS BEGIN INSERT INTO @result SELECT * FROM dbo.GetListOfSquaresForShippingLot(@ShippingLot)
I am databinding a dataset formed from a stored procedure,(all done on page_load). However, the reference to the column name is not recognised with the following error being returned. Column with name "CalcVal" was not found. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.ArgumentException: Column with name "CalcVal" was not found.Source Error:
Line 152: chartCommand.Fill(chartDs); Line 153: Chart1.DataSource = chartDs; Line 154: Chart1.DataBind(); Line 155: Line 156: } This worked before deployment and the other controls which are bound to data using stored procedures seem to work. However, these other data sources are all sqlDatasoure controls. Any suggestions would be helpful. I have found issues relating the to user ID and password which seems to depend on whether the web server and data server are the same machine or whether they are remote from each other. cheers-jim.