Best Way To Reference A Table With A Composite Key?
Nov 24, 2006
The table above is my users table. It allows for a user to be at multiple sites or multiple locations within a single site or multiple sites.
Would it be wise to use a auto incrementing primary key instead of the 3 column composite key?
The reason I ask is because if I am referencing this SU table (which I will be a lot), a lot more data would be replicated to the tables which have the foreign key to this table, right?
But if I used a single incrementing column as the primary key, only a small integer would be used as the foreign key, saving space?
Does this make sense?
Hi All, Can anyone tell me how to create a reference for composite key. For ex, I have created tblEmp table successfully. create tblEmp( empId varchar(100), RegId varchar(100), empname varchar(100),constraint pk_addprimary key(empId, RegId) ) And now, I am going to create another table which references the composite key.create table tblAccount( acctId varchar(100) primary key, empId varchar(100) references tblEmp(empId), RegId varchar(100) references tblEmp(RegId) ) But it gives error like Server: Msg 1776, Level 16, State 1, Line 1There are no primary or candidate keys in the referenced table 'tblEmp' that match the referencing column list in the foreign key 'FK__tbl'.Server: Msg 1750, Level 16, State 1, Line 1Could not create constraint. See previous errors. Could anyone please let me know how to create reference for composite key. Thanks in advance,Arun.
I have a table which has a composite primary key consisting of four columns, one of them being a datetime called Day.
The nice thing afaik with this composite key is that it prevents duplicate entries in the table for any given day. But the problem is probably two-fold
1. multiple columns need to be used for joins and I think this might degrade performance? 2. in client applications such as asp.net these primary keys must be sent in the query string and the query string becomes long and a little bit unmanagable.
A possible solutions I'm thinking of is dropping the existing primary key and creating a new identity column and a composite unique index on the columns from the existing composite key.
I would like to have some tips, recommendations and alternatives for what I should do in this case.
Hi all, well i want to have an web-based database application in which in an single webform , i need to insert the values to 5 different tables. here empid is primary key (PK) in one table and in the rest of the tables its an Foreign Key(FK) my question is, how can i create these tables with composite key? ie, i want to creat an table which will have FK and as well another key which both will uniquely idenitfies a row. Well i am using SQL server 2000 and i wish to create these tables using the enterprise manager. here are the tables 1) empidtable empid,fname,lname 2)empcountrytable empid,country 3)empvisatable empid,visa 4)empdoctable empid,doc 5)empfile empid,filename,filecontenttype,filesize,filedata Plz do help me thanx in advance
I have three tables that are important here, a 'Plant' table a 'Spindle' table and a 'PlantSpindle' table. The 'PlantSpindle' is comprised of a PlantID and a SpindleID acting as the Primary Key for the table with no other fields.
I have an aspx page that captures the appropriate data to create an entry in the Spindle table. Depending on the user, I will know which plantID they are associated with via a querystring. In my storedproc I insert the data from the webform into the Spindle table but get stuck when I try to also insert the record into the PlantSpindle table with the PlantID I have retrieved via the querystring and the SpindleID of the spindle record the user just created. Basically, I am having trouble retrieving that SpindleID.
Here is what I have in my storedProc (truncated for brevity).
AS SET NOCOUNT ON INSERT INTO Spindle (plantHWG, spindleNumber, spindleDateInstalled, spindleDateRemoved, spindleDurationMonths, spindleBearingDesignNumber, spindleArbor, spindleFrontSealDesign, spindleFrontBearing, spindleRearBearing, spindleRearSealDesign, spindleNotes) VALUES (@plantHWG, @spindleNumber, @spindleDateInstalled, @spindleDateRemoved, @spindleDurationMonths, @spindleBearingDesignNumber, @spindleArbor, @spindleFrontSealDesign, @spindleFrontBearing, @spindleRearBearing, @spindleRearSealDesign, @spindleNotes)
SET @spindleID = (SELECT @@Identity FROM Spindle)
INSERT INTO PlantSpindle (plantID, SpindleID)
VALUES (@plantID, @SpindleID)
I have guessed at a few different solutions but still come up with Procedure 'InsertSpindle' expects parameter '@spindleID', which was not supplied when I execute the procedure.
I am trying to add indexes to my table data types and have realized that I can only add primary keys. So, I am hoping there is a way to add a composite primary key, but I am not having any success. I have tried the following:
NOTE: I am not interested in any responses that want to argue the use of a unique ID field and autonumbering as the PK. It is quite clear from the forums that this subject is a polarizing one. This question is for those who follow text-book design practices and believe that a composite primary key should be used when it is available. I want to be one of them for the time being.
SYNOPSIS: I have three tables, TestSummary, TestDetails, and Steps.
The TestSummary table looks like this:
Create table TestSummary ( TestSummaryID int identity primary key, ... SequenceID int not null )
It contains the date and time of the test, the serial number, the part number, the test operator's name, and the ID of the sequence of steps used during the test. It uses a unique ID field for the primary key.
The TestDetails table looks like this:
Create table TestDetails ( TestDetailsID int identity primary key, TestSummaryID int not null, StepID int not null, ... )
It contains the details of the test like voltage readings, current readings, temperature, etc., one record per reading. It also contains the step number of the test sequence specified in the TestSummary table.
The Steps table looks like this:
Create table Steps ( SequenceID int not null, StepID int not null, Function int not null Primary key (SequenceID, StepID) )
It contains a list of all of the functions to be performed on the device under test by sequence number and the step number within the sequence.
When I try to establish a relation between TestSummary.SequenceID and Steps.SequenceID, SQL Server flags an error because TestSummary.SequenceID and Steps.SequenceID:Steps.StepID do not match.
Is is possible to create a composite primary key on a table variable?Neither of these two statements are successful:DECLARE @opmcjf TABLE (jobdetailid INT NOT NULL,cjfid INT NOT NULL,cjfvalue VARCHAR(100) NULL)ALTER TABLE @opmcjf ADD CONSTRAINT [PK_opmcjf] PRIMARY KEY CLUSTERED([jobdetailid],[cjfid])andDECLARE @opmcjf TABLE (jobdetailid INT PRIMARY KEY,cjfid INT PRIMARY KEY,cjfvalue VARCHAR(100) NULL)Thanks,Shaun
I have a requirement of table partitioning. we have 10 years of data on a table which is 30 billion up rows on 2005 server we are upgrading it to 2014. we have to keep 7 years of data. there is no keys on table or date column. since its a huge amount of data and many users its slow down the process speed. we are thinking to do partition on 7 years for Quarterly based. but as i said there is no date column on table we have to use reference table to get date. is there a way i can do the partitioning with out adding date column on table? also does partition will make query faster?
I have think three ways to do it. 1. leave as it is. 2. 7 years partition on one server 3. 3 years partition on server1 and 4 years partition on server2 (for 4 years is snapshot better?)
Hello,I have a query that I need help with.there are two tables...Product- ProductId- Property1- Property2- Property3PropertyType- PropertyTypeId- PropertyTypeThere many columns in (Product) that reverence 1 lookup table (PropertyType)In the table Product, the columns Property1, Property2, Property3 all contain a numerical value that references PropertyType.PropertyTypeIdHow do I select a Product so I get all rows from Product and also the PropertyType that corresponds to the Product.Property1, Product.Property2, and Product.Property3ProductId | Property1 | Property2 | Property3 | PropertyType1 | PropertyType2 | PropertyType3 PropertyType(1) = PropertyType for Property1PropertyType(2) = PropertyType for Property2PropertyType(3) = PropertyType for Property3I hope this makes sence.Thanks in advance.
I am using vs 2010 to write my dtsx import scripts.I use a script component as a source to create a flat file destination file.Everything have been working fine,but then my development machine crashed and we have to install everything again.Now when i use the execute package utility to test my scripts i get the following error:
Error system.NullReferenceException: Object refrence not set to an instance reference.
In PreExecute section TextReader = new system.io.streamreader(" file name") In the CreateNewOutputRows: dim nextLine as string nextLine = textReader.ReadLine
[code]...
is there something which i did not install or what can be the error?
Given a UDT, is there any way to get a reference to the table where the specific instance is running ?
IE: Let's suppose we have defined a UDT named UDTPoint; now we define two tables: ATable & BTable, wich both have one column that is defined as UDTPoint.
When an insert/update/delete operation on ATable or BTable occurs, the UDTPoint class needs to verify in which context it is running (ATable or BTable) before doing operations on data.
I have 2 databases in sql server. let us say database1 = db1 and database2 = db2 Now both the databases have a same table called table1 with the same fields.
IF data in db1.table1 is updated then data in db2.table2 should be updated automatically.
There are many ways we can do this. one way is to create a INSERT trigger on db1.table1.
But i would like to avoid trigger Is there something in SQL server where I can just link table1 of db1 to db2 and delete the table1 in db2. That means db2 is using the same table that of db1.
I am new to this site and I hope anyone out there can help me. I was tasked to change the constraints of my existing table. Lets call it table1. This table has an attribute that needs to take the value of another attribute of another table ( let's call it tables2) and that attribute must satisfy a certain expression ( I suppose I can isolate it by using the select statement ).
I would like to know if it's possible in MS SQL to redirect a table into another DB instance? I have no access into the source code and I have been wondering if it is possible to make a redirection/hard link in MS SQL side.
I would have a table in my base DB and when a query is made into this table, the MS SQL would redirect it to another DB or table. Is this possible in MS SQL ? Something along the lines of a hard-link in linux. Thank you very much.
Hi All, The problem is about cross reference. 1. I have a third party cross reference store procedure SimpleXTab CREATE PROCEDURE [dbo].[SimpleXTab2] @XField varChar(50), @XTable varChar(100),@XWhereString varChar(250), @XFunction varChar(10), @XFunctionField varChar(50), @XRow varchar(300),@ResultTable varchar(100) ASDeclare @SqlStr nvarchar(4000)Declare @tempsql nvarchar(4000)Declare @SqlStrCur nvarchar(4000)Declare @col nvarchar(100) set @SqlStrCur = N'Select [' + @XField + '] into ##temptbl_Cursor from [' + @XTable + '] ' + @XWhereString + ' Group By [' + @XField + ']' /* select @sqlstrcur */exec sp_executesql @sqlstrcur
declare xcursor Cursor for Select * from ##temptbl_Cursor open xcursor Fetch next from xcursor into @Col While @@Fetch_Status = 0Begin set @Sqlstr = @Sqlstr + ", " set @tempsql = isnull(@sqlstr,'') + isnull(@XFunction + '( Case When ' + @XField + " = '" +@Col + "' then [" + @XFunctionField + "] Else 0 End) As [" + @Col + "]" ,'') set @Sqlstr = @tempsql Fetch next from xcursor into @Col End /* Select @Sqlstr as [mk], len(@sqlstr) as [leng] */ set @tempsql = 'Select ' + @XRow + ', ' + @Sqlstr + 'into ' +@ResultTable+' From ' + @XTable + @XWhereString + ' Group by ' + @XRowprint @tempsql set @Sqlstr = @tempsql Close xcursor Deallocate xcursor set @tempsql = N'Drop Table ##temptbl_Cursor' exec sp_executesql @tempsqlprint @tempsql /* Select @Sqlstr as [mk], len(@sqlstr) as [leng] */print @sqlstr exec sp_executesql @Sqlstr if @@rowcount = 0 select 'No Records found'GO 2. I've use this store procedure for many cross reference successfully. But this time my cross reference value (resultcode) is a varchar which cannot be convert to int or decimal in sql, Probably, you've noticed that the fourth parameter is a function. how can i modify SimpleXtab to avoid using math function but still can generate cross reference. exec simplextab2 'Sequence','##tbltempreport',' ','sum','resultcode','Parameter' ,'dbo.resultcodetable'
I need to write a query that requires respective fields referencing from multiple tables. For example, here are the tables: Main Table: InfoID Team1 Player1 Team1 Table: Player_ref Player Team_Player_ref Player1 John doh Table: Team_ref Team Team_Player_ref Team1 My Team
Ideal result Table from query: InfoID Count John Doh 1 My Team 2
Any suggestion to creat the Ideal Results table from query? Normally, I could do it if it only referenced from 1 table, I would do an inner join, however, since there are 2 referenece table, doing inner join wouldn't work. A proposed suggestion would certainly be nice. Thanks in advance. --daydreamstuck at the current problem
I am trying to write a query that will use tables in more than one SQL database (on the same server). How do refer to the table? I have tried dbasename.tablename.fieldname but I don't think that's working.
Does anyone know if MS SQL can't process a "select * from deleted" from within a cursor that's embedded in a trigger? I'm getting an error when I run this...
DECLARE check_contact_fields CURSOR FOR SELECT field_id, column_name FROM contacts_fields OPEN check_contact_fields FETCH NEXT FROM check_contact_fields INTO @field_id, @column_name WHILE (@@FETCH_STATUS = 0) BEGIN set @SQL = 'select ' + @column_name + ' into ##DeletedData from deleted' exec sp_executesql @SQL set @SQL = 'select ' + @column_name + ' into ##InsertedData from inserted' exec sp_executesql @SQL if (select * from ##DeletedData) <> (select * from ##InsertedData) select * from ##InsertedData FETCH NEXT FROM check_contact_fields INTO @field_id, @column_name END CLOSE check_contact_fields DEALLOCATE check_contact_fields
drop table ##DeletedData drop table ##InsertedData
Server: Msg 208, Level 16, State 1, Line 1 Invalid object name 'deleted'.
The script below can be used to determine the reference levels of all tables in a database in order to be able to create a script to load tables in the correct order to prevent Foreign Key violations.
This script returns 3 result sets. The first shows the tables in order by level and table name. The second shows tables and tables that reference it in order by table and referencing table. The third shows tables and tables it references in order by table and referenced table.
Tables at level 0 have no related tables, except self-references. Tables at level 1 reference no other table, but are referenced by other tables. Tables at levels 2 and above are tables which reference lower level tables and may be referenced by higher levels. Tables with a level of NULL may indicate a circular reference (example: TableA references TableB and TableB references TableA).
Tables at levels 0 and 1 can be loaded first without FK violations, and then the tables at higher levels can be loaded in order by level from lower to higher to prevent FK violations. All tables at the same level can be loaded at the same time without FK violations.
Tested on SQL 2000 only. Please post any errors found.
Edit 2006/10/10: Fixed bug with tables that have multiple references, and moved tables that have only self-references to level 1 from level 0.
This script finds table references and ranks them by level in order to be able to load tables with FK references in the correct order. Tables can then be loaded one level at a time from lower to higher. This script also shows all the relationships for each table by tables it references and by tables that reference it.
Level 0 is tables which have no FK relationships.
Level 1 is tables which reference no other tables, except themselves, and are only referenced by higher level tables or themselves.
Levels 2 and above are tables which reference lower levels and may be referenced by higher levels or themselves.
declare @table table ( TABLE_NAME nvarchar(200) not null primary key clustered ) set nocount off
print 'Load tables for database '+db_name()
insert into @table select TABLE_NAME = a.TABLE_SCHEMA+'.'+a.TABLE_NAME from INFORMATION_SCHEMA.TABLES a where a.TABLE_TYPE = 'BASE TABLE'and a.TABLE_SCHEMA+'.'+a.TABLE_NAME <> 'dbo.dtproperties' order by 1
print 'Load PK/FK references' insert into @r selectdistinct PK_TABLE = b.TABLE_SCHEMA+'.'+b.TABLE_NAME, FK_TABLE = c.TABLE_SCHEMA+'.'+c.TABLE_NAME from INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS a join INFORMATION_SCHEMA.TABLE_CONSTRAINTS b on a.CONSTRAINT_SCHEMA = b.CONSTRAINT_SCHEMA and a.UNIQUE_CONSTRAINT_NAME = b.CONSTRAINT_NAME join INFORMATION_SCHEMA.TABLE_CONSTRAINTS c on a.CONSTRAINT_SCHEMA = c.CONSTRAINT_SCHEMA and a.CONSTRAINT_NAME = c.CONSTRAINT_NAME order by 1,2
print 'Make copy of PK/FK references' insert into @rs select * from @r order by 1,2
print 'Load un-referenced tables as level 0' insert into @t select REF_LEVEL = 0, a.TABLE_NAME from @table a where a.TABLE_NAME not in ( select PK_TABLE from @r union all select FK_TABLE from @r ) order by 1
-- select * from @r print 'Remove self references' delete from @r where PK_TABLE = FK_TABLE
declare @level int set @level = 0
while @level < 100 begin set @level = @level + 1
print 'Delete lower level references' delete from @r where PK_TABLE in ( select TABLE_NAME from @t ) or FK_TABLE in ( select TABLE_NAME from @t )
insert into @t select REF_LEVEL =@level, a.TABLE_NAME from @table a where a.TABLE_NAME not in ( select FK_TABLE from @r ) and a.TABLE_NAME not in ( select TABLE_NAME from @t ) order by 1
if not exists (select * from @r ) begin print 'Done loading table levels' print '' break end
end
print 'Count of Tables by level' print ''
select REF_LEVEL, TABLE_COUNT = count(*) from @t group by REF_LEVEL order by REF_LEVEL
print 'Tables in order by level and table name' print 'Note: Null REF_LEVEL nay indicate possible circular reference' print '' select b.REF_LEVEL, TABLE_NAME = convert(varchar(40),a.TABLE_NAME) from @table a left join @t b on a.TABLE_NAME = b.TABLE_NAME order by b.REF_LEVEL, a.TABLE_NAME
print 'Tables and Referencing Tables' print '' select b.REF_LEVEL, TABLE_NAME = convert(varchar(40),a.TABLE_NAME), REFERENCING_TABLE =convert(varchar(40),c.FK_TABLE) from @table a left join @t b on a.TABLE_NAME = b.TABLE_NAME left join @rs c on a.TABLE_NAME = c.PK_TABLE order by a.TABLE_NAME, c.FK_TABLE
print 'Tables and Tables Referenced' print '' select b.REF_LEVEL, TABLE_NAME = convert(varchar(40),a.TABLE_NAME), TABLE_REFERENCED =convert(varchar(40),c.PK_TABLE) from @table a left join @t b on a.TABLE_NAME = b.TABLE_NAME left join @rs c on a.TABLE_NAME = c.FK_TABLE order by a.TABLE_NAME, c.PK_TABLE
Hello all,I have two tables - Projects and ProjectStructTable Projects contains master records of the projects, ProjectStructallows to define a project herarchie and contains the fieldsPrjStructId, ProjectId, PrjStructName, ..., ParentIdPrjStructParent contains a reference to the parent or to itselves ifrecord is top-level-record for a project.I try to create a trigger on table Projects (INSERT) whichautomatically creates the top-level-entry in ProjectStruct but Ididn't succed.Tried to use (several variations similar to)INSERT INTO ProjectStruct (ProjectId, PrjStructName, ParentId)SELECT prjProjectId, 'top-level',IDENT_CURRENT('ProjectStruct'))FROM INSERTEDbut this inserts a reference to the last inserted record. Why thishappens is pretty clear to me, but I found no way to get the referenceto the identity column of the record currently inserted.Is there a way to do this?
I need a table of seasonally adjusted forecasts. Each row contains 52 weekly values to been named as needed (e.g. Week01, Week02, etc.). At any point in the year, I want to be able to determine how many weeks I can cover with the product on hand.
I have not been able to envision a set based, normalized solution given there are nearly a million items to be evaluated daily. If I normalize, I'm faced with 52 million rows. It seems to me I'm better off bringing a wide row containing all 52 week buckets into memory and working with them in a stored procedure. And if that's the best solution, how do I reference these "virtual" buckets? I'm thinking of some kind of While() loop that counts the weeks until the inventory is exhaused but I need a subscript based technique to reference each week.
I have a common requirement (when I'm processing data rows from an input file) to perform some data manipulation in script then look up a value from a reference table and perform some further data manipulation depending on whether a matching value was found in the lookup table or not.
For example, say I'm processing Customer data rows and the first "word" (/token) of the FullName column might be a title or the title could be missing and it might be a forename or initial instead. I want to check the first word of this FullName column to see if it matches any valid title values in a ReferenceTitles lookup table. If I find a match I want to set my Title column to the value from the ReferenceTitles lookup table, otherwise I want to set it to, say, an empty string. Then I want to process the rest of the FullName column tokens differently depending on whether or not a match was found.
It seems very messy to start coding a script transformation and then have to use a lookup transformation combined with a script transformation on the error output followed by a union and a sort and finally a further script transformation (especially as I would like to be able to use variables from the first script in the later processing)...
So what I'm wondering is: Is there an easy/clean way to perform a database lookup (using cached values) from a script so that I can achieve all the above from within a single script component?
In general we cannot delete a table if it refers another table. But in the process of backup and restore, we need to delete all the tables, so we have return an asp.net function...
Dim Datatable As String Dim ds As New DataSet ds = gDatabase.ExecuteQuery(" select Table_Name from Information_schema.Tables where Table_type='TABLE'") If ds.Tables.Count > 0 Then If ds.Tables(0).Rows.Count > 0 Then Dim dr As DataRow Dim da As SqlCeDataAdapter Dim Cmd As String For Each dr In ds.Tables(0).Rows Datatable = dr.Item("Table_name") Cmd = "Delete from [" & Datatable & "]" gDatabase.ExecuteNonQuery(Cmd) Next End If End If
we got an error like
"Msg 4712, Level 16, State 1, Line 1 Cannot truncate table 'Electricalworks' because it is being referenced by a FOREIGN KEY constraint. "
how to override these errors, if we have to delete all the tables. We have about 200 tables.
Several years ago, I am sure that I had a query that either read from or wrote to a text file. There was some way to: select * into 'c:\out.txt' from SomeTable Does anyone know if this functionality exists? If so, what is the syntax?
--If I pass activityId 3 or 2 or 4 it should return 0 as none of the activity is circular but If I pass 5, 6 or 7 it should return 1 as they have circular reference....
I need a sql qry which will require to find a circular reference in it.....
As in above sample of data ,If I pass activityId 3 or 2 or 4 to qry it should return 0 as none of the activity is circular but If I pass 5, 6 or 7 it should return 1 as they have circular reference....
This function will generate all DELETE statements in correct order to perform a CASCADING delete. For self-joined tables, it will generate the T-SQL code to "unwind" the table, also in correct order!CREATE FUNCTION dbo.fnCascadingDelete ( @Schema NVARCHAR(128) = NULL, @Table NVARCHAR(128) = NULL ) RETURNS@Return TABLE ( RowID INT PRIMARY KEY CLUSTERED, IsSelfJoin TINYINT NOT NULL, HasPk TINYINT NOT NULL, [SQL] NVARCHAR(4000) NOT NULL ) AS BEGIN DECLARE@Constraints TABLE ( RowID INT NOT NULL, Indent SMALLINT NOT NULL, [Catalog] NVARCHAR(128) NOT NULL, [Schema] NVARCHAR(128) NOT NULL, [Table] NVARCHAR(128) NOT NULL, [Column] NVARCHAR(128), pkCatalog NVARCHAR(128), pkSchema NVARCHAR(128), pkTable NVARCHAR(128), pkColumn NVARCHAR(128), pkType NVARCHAR(128), pkSize INT, IsSelfJoin TINYINT NOT NULL, HasPk TINYINT NOT NULL )
INSERT@Constraints ( RowID, Indent, [Catalog], [Schema], [Table], [Column], pkCatalog, pkSchema, pkTable, pkColumn, pkType, pkSize, IsSelfJoin, HasPk ) SELECTRowID, Indent, [Catalog], [Schema], [Table], [Column], pkCatalog, pkSchema, pkTable, pkColumn, pkType, pkSize, SelfJoin, CASE WHEN [Column] IS NULL THEN 0 ELSE 1 END FROMdbo.fnTableTree(@Schema, @Table)
IF @@ROWCOUNT = 0 RETURN
DECLARE@SQL TABLE ( ID INT IDENTITY(1, 1), RowID INT PRIMARY KEY CLUSTERED, IsSelfJoin TINYINT NOT NULL, HasPk TINYINT NOT NULL, [SQL] NVARCHAR(4000) NOT NULL )
DECLARE@Unwind TABLE ( RowID INT NOT NULL, StepID INT IDENTITY(0, 1) PRIMARY KEY NONCLUSTERED, [SQL] NVARCHAR(4000) )
WHILE NOT EXISTS (SELECT * FROM @SQL WHERE RowID = 1) BEGIN SELECT TOP 1@RowID = c.RowID, @ID = c.RowID, @Indent = c.Indent, @TSQL = N'', @EndSQL = N'', @IsSelfJoin = c.IsSelfjoin, @HasPk = c.HasPk FROM@Constraints AS c LEFT JOIN@SQL AS s ON s.RowID = c.RowID WHEREs.RowID IS NULL ORDER BYc.Indent DESC, c.RowID DESC
WHILE @ID > 0 BEGIN IF @Indent = 0 SELECT@RowSQL = N'DELETE t' + CAST(@RowID AS NVARCHAR(12)), @RowSQL = @RowSQL + N' FROM ' + QUOTENAME(c.[Catalog]) + N'.' + QUOTENAME(c.[Schema]) + N'.' + QUOTENAME(c.[Table]) + N' AS t' + CAST(@ID AS NVARCHAR(12)), @EndSQL = N' WHERE t' + CAST(@ID AS NVARCHAR(12)) + '.' + QUOTENAME(COALESCE(c.[Column], '%0')) + N' = ''%1''', @IsSelfJoin = @IsSelfJoin | c.IsSelfJoin FROM@Constraints AS c WHEREc.RowID = @ID ELSE SELECT@RowSQL = N' INNER JOIN ' + QUOTENAME(c.[Catalog]) + N'.' + QUOTENAME(c.[Schema]) + N'.' + QUOTENAME(c.[Table]), @RowSQL = @RowSQL + N' AS t' + CAST(@ID AS NVARCHAR(12)) + N' ON t' + CAST(@ID AS NVARCHAR(12)) + N'.' + QUOTENAME(c.[Column]), @pkColumn = QUOTENAME(c.pkColumn), @IsSelfJoin = @IsSelfJoin | c.IsSelfJoin FROM@Constraints AS c WHEREc.RowID = @ID
SELECT TOP 1@ID = c.RowID, @Indent = c.Indent, @RowSQL = @RowSQL + N' = t' + CAST(c.RowID AS NVARCHAR(12)) + N'.' + @pkColumn, @IsSelfJoin = @IsSelfJoin | c.IsSelfJoin FROM@Constraints AS c WHEREc.RowID < @ID AND c.Indent < @Indent ORDER BYc.Indent DESC, c.RowID DESC
INSERT@Stage (Lvl, RowKey) SELECT@Lvl, t.' + QUOTENAME(@pkColumn) + ' FROM' + QUOTENAME(@Catalog) + '.' + QUOTENAME(@Schema) + '.' + QUOTENAME(@Table) + ' AS t INNER JOIN@Stage AS s ON s.RowKey = t.' + QUOTENAME(@Column) + ' AND s.Lvl = @Lvl - 1 LEFT JOIN@Stage AS cr ON cr.RowKey = t.' + QUOTENAME(@pkColumn) + ' WHEREcr.RowKey IS NULL END SELECT ''DELETE FROM ' + QUOTENAME(@Catalog) + '.' + QUOTENAME(@Schema) + '.' + QUOTENAME(@Table) + ' WHERE ' + QUOTENAME(@pkColumn) + ' = '' + QUOTENAME(RowKey, '''''''') FROM @Stage WHERE RowID > 0 ORDER BY RowID DESC'
INSERT@Unwind ( RowID, [SQL] ) VALUES( @RowID, @RowSQL ) END END
INSERT@Return ( RowID, IsSelfJoin, HasPk, [SQL] ) SELECTs.ID, s.IsSelfJoin, s.HasPk, CASE WHEN u.RowID IS NULL THEN s.[SQL] ELSE u.[SQL] END FROM@SQL AS s LEFT JOIN@Unwind AS u ON u.RowID = s.RowID ORDER BYs.ID, u.StepID
In BOL it says: "The Lookup transformation performs an equi-join between values in the transformation input and values in the reference dataset. Using an equi-join means that each row in the transformation input must match at least one row from the reference dataset. If there is no matching entry in the reference dataset, no join occurs and no values are returned from the reference dataset. This is an error, and the transformation fails, unless it is configured to ignore errors or redirect error rows to the error output. "
I have a lookup transformation which is supposed to find a match on two fields in the reference dataset (a table in my case) but strangely, when I execute my package and the reference table is empty the lookup still finds match for each row of my input dataset.
Does anyone have an idea why? I could'nt find anything about that in BOL.
Hi everybody. I created an application role in a database (DB1) and gave it all the rights on a view in DB1 which refers to a table located in another db (DB2). I also gave the rights to the app role on a table of DB1 I tried to use this app. role through the sp_setapprole launched by a user (server principal?) which is SQL Server administrator (and local administrator (Win 2003 Server)). With the following query SELECT USER_NAME()
I see that the approle is being used. Than, if I query the table on DB1 everything works, but if I query the view, referring a table in db2 I get following error:
The server principal "NameOfServerPrincipal" is not able to access the database "DB2" under the current security context. What should I do to make it work?
The table in DB2 has the same schema of the view in DB1 which refers to it. I put the DB1 TrustWorthy and both the database have the db_chaining option activated.
Any idea on how to solve the problem would be widely appreciated. Thank you very much. Vania