Writting A Table

Feb 13, 2001

Hello,
I have to write a trigger to truncate at a scheduled time.Truncate statement is not allowed in the trigger.What should I do.I mean how to go for it.
Thanks for any help.
JAY

View 3 Replies


ADVERTISEMENT

Writting Trigger Or Procedure To Delete Duplicate Entries In A Table?

Sep 3, 2007

I am using Sql Server 2000.
I have a customer table with fields - CustId, Name, Address, City, StdCode, Phone.
I used to insert entries in this table from an excel file.
One excel file will contain thousands of customer.
In this table combination of StdCode and Phone should not be repeated.
If I do it in my VB.Net coding.then application gets drastically slow.
So I want to write a procedure or trigger for this.
Here what I will do, I will send all records into database then this trigger or procedure will check for
any existing entry of combination of StdCode and phone. If entry exists then this will delete new entry
or will not allow this new entry.
Is this possible to do using Trigger or stored procedure?

View 5 Replies View Related

VB6 && VB2005 Runtime Error When Writting To Access Database Table

May 1, 2007

In both VB6 and VB2005 Both are loaded on same computer. When attempting to write to an access database table using ADO I get a runtime error: -2147217887(80040e21) "mutiple-step operation generates errors. Check each status value. " Reading the database is no problem. I only get the errors when writting to database. I have used the following code forever in VB6 and never got this error. Now that I have Visual Studio 2005 loaded on the same machine. I get this error. I get the exact same error when using this code in VB2005. I know VB6 but am just learning 2005. The following code is writting to a database table from various user imputed text and combo boxes. I used basicly the same code in VB2005 and get the same exception error. This code works on machines that do not have VB .net loaded. How do I fix this. My application is useless unless the user can make changes to their data.



Public Function ActionToDb()
Dim noPo As Integer
Dim SQL As String, rst As ADODB.Recordset, dataSourceName As String

dataSourceName = DBPATH & "LVBURV Database.mdb"
dbConn.ConnectionString = "DBQ=" & dataSourceName & ";Driver={Microsoft Access Driver (*.mdb)}"
dbConn.Open

On Error GoTo ErrorHandler

Set rst = New ADODB.Recordset
With rst
SQL = "Select [mLVbuNo], [mStratInit], [mMerticLv],[mSubMetLv],[mTaskAction],[mImpact]," & _
"[mStatus], [mOwner], [mTitle],[mOrigDate],[mCurrentDate],[mCopmpleteDt],[mComment],[mSource]," & _ "[mStatColor],[mHyperlink],[CompCheck] From [tblMasterActionItem]"
.CursorLocation = adUseClient
.Open SQL, dbConn, adOpenKeyset, adLockBatchOptimistic, adCmdText
noPo = .RecordCount
'If .RecordCount > 0 Then
.MoveLast
.AddNew
rst.Fields("mLVbuNo") = giRecNo
rst.Fields("mStratInit") = frmActionDe.cboStatInit.Text
rst.Fields("mMerticLv") = frmActionDe.cboMetricLever.Text
rst.Fields("mSubMetLv") = frmActionDe.cboSubMet.Text
rst.Fields("mTaskAction") = frmActionDe.txtTask.Text
rst.Fields("mImpact") = frmActionDe.txtImpact.Text
rst.Fields("mStatus") = frmActionDe.txtStatus.Text
rst.Fields("mOwner") = frmActionDe.cboOwn.Text
rst.Fields("mTitle") = gstOwnT
rst.Fields("mOrigDate") = frmActionDe.txtOrigDt.Text
rst.Fields("mCurrentDate") = frmActionDe.txtCurDt.Text
rst.Fields("mCopmpleteDt") = frmActionDe.txtCompDt.Text
rst.Fields("mComment") = frmActionDe.txtComments.Text
rst.Fields("mSource") = frmActionDe.cboSource.Text
rst.Fields("mStatColor") = frmActionDe.txtStatColor.Text
rst.Fields("mHyperlink") = frmActionDe.txtHyperlink.Text
If optCompCheck.Value = True Then
rst.Fields("CompCheck") = True
Else
rst.Fields("CompCheck") = False
End If
'End If
.Update
.Close
End With
dbConn.Close

ExitSub:
On Error Resume Next
dbConn.Close
Set rst = Nothing
Set dbConn = Nothing
Exit Sub
ErrorHandler:
WriteToErrorLogEnd Err.Description & " in ActionToDb"
Resume

End Function

View 6 Replies View Related

Writting A Trigger

Feb 13, 2001

Hello,
I have to write a trigger to truncate a table at a scheduled time.Truncate statement is not allowed in the trigger.What should I do.I mean how to go for it.How can I test my trigger if it's working fine or not.
Thanks for any help.
JAY

View 2 Replies View Related

Can Anybody Help To Writting This Query

Jun 25, 2007

I have table name employee with attributes like eno,ename dno,salary. My problem is that i need select complete information of the emloyee's when employee getting same salary in same depatment.

Eg: I have the table like this
eno ename dno salary
1 Noor D10 10000.50
2 Ahmed D20 20000.75
3 jaya D30 15000.65
4 hema D10 10000.50
5 rupa D20 20000.75
6 prabha D40 20000.75
7 lalitha D40 12000.75
8 vetri D40 12000.75
and i need the output as fallows

eno ename dno salary
1 Noor D10 10000.50
4 hema D10 10000.50
7 lalitha D40 12000.75
8 vetri D40 12000.75
2 Ahmed D20 20000.75
5 rupa D20 20000.75

so I written the query like this

SELECT * FROM employee
where dno in(SELECT dno FROM employee
group by dno,salary
having count(dno)>1) and
salary in(SELECT salary FROM sub
group by dno,salary
having count(salary)>1)

but i got the output as fallows

eno ename dno salary
1 Noor D10 10000.50
4 hema D10 10000.50
7 lalitha D40 12000.75
8 vetri D40 12000.75
2 Ahmed D20 20000.75
5 rupa D20 20000.75
6 prabha D40 20000.75
so plz somebody help me to get the output what i need........


Noor Ahmed
Keysoft solution

View 6 Replies View Related

Writting Into AS400

Jul 2, 2007

Hallo

We got a €œSql Server€? and an €œAS400€? System. I can Read the information from the AS400 using a DataReader- Source my problem ist that I can not manage to write in the €œAS400€?. Using a DataReader- Destination I am not able to specify the destination table.

Does any one know what I am missing to Configure?

View 4 Replies View Related

Question About Writting A Trigger

May 1, 2008

hello.

i have two table so that they are following form:

tblCardex(Fd_GoodsId,Fd_RepositoryId,Fd_DateTime,Fd_Type,Fd_UnitCoefficent)

tblGoodsStock(Fd_GoodsId,Fd_RepositoryId,Fd_UnitCoefficent)

Fd_GoodsId,Fd_RepositoryId -->inteager
Fd_UnitCoefficent --> decimal
Fd_Type --> bit (0 means input and 1 means output)

i wish writting a trigger on Insert of tblCardex.in this trigger ,i must do following operations:

if(tblGoodsStock.Fd_GoodsId=Inserted.Fd_GoodsId and tblGoodsStock.Fd_RepositoryId=Inserted.Fd_RepositoryId)
begin

if(Inserted.Fd_Type==0)
tblGoodsStock.Fd_UnitCoefficent = tblGoodsStock.Fd_UnitCoefficent+
Inserted.Fd_UnitCoefficent

else --Inserted.Fd_Type==1
tblGoodsStock.Fd_UnitCoefficent = tblGoodsStock.Fd_UnitCoefficent-
Inserted.Fd_UnitCoefficent

end

tank you.

View 5 Replies View Related

Problem At Writting Triggers

Oct 6, 2006

hi,
here i had created two table named table1,table. both the tables are homogenously belongs to same group. if i eneter any data say pinno in table1 the same pinno has to be enterd into table so i had wirtten a trigger for table here like this:
create trigger Tg_Table1 on Table1
for insert as
insert into Table2(pinno)
select pinno as pinno from table1.
the query is getting compiling correctly but the data entered into table2 while entering into the table1 is coming with duplicate values like:
output of table2:
pinno
1001 -> when i inserted 1001 in table1
1001 -> when i inserted 1002 in table1
1002
1001 -> when i inserted 1003 in table1
1002
1003

the column name pinno in table1 is also same for table2.

intially i had primary keys for two tables for column pinno. at that time it has shown error wqhile i am trying to insert data into table1.
so i dropped the PK constarint for table2. this time the out put coming with replicated values.

pls some one show me a way to clear this problem

One can never consent to creep,when one feels an impulse to soar
RAMMOHAN

View 1 Replies View Related

Writting To Multiple Tables

Feb 14, 2006

Hi All,

I need to read data from a table, on a remote server, and write the data to an identical table on the local server. (That I did and all works fine.) The local server is were we do analysis services. So, with the data from the remote, I need to write parts of it to 2 tables other than the local identical table. (I hope this is clear) What tools do I use to accomplish this?

If this is not clear, let me know and I will try to clarify.

Your help is very much appreciated.

Thanks,

Roy

View 1 Replies View Related

Writting Column Names Dynamically

Feb 28, 2008

Can someone please help I'm writting the following query.
SELECT
(SELECT c.column_name FROM information_schema.tables T
JOIN information_schema.columns C
ON t.table_name = c.table_name
WHERE t.table_type = 'base table' and t.table_name like 'L_%' )
INTO #TempTable FROM TableA A LEFT JOIN [Server-Name].DB_Name.dbo.TableB B ON A.ID = B.ID

I'm trying to put commas between column names. How do I go about doing that?

View 16 Replies View Related

Writting Multiple Rows From One Input Row

Apr 7, 2006

Hi:

I'm trying to write a transformation script to write multiple rows from 1 input row. In SQL Server 2000 DTS I could do this by using DTSTransformStat_SkipFetch and DTSTransformStat_SkipRow. In SQL server 2005 it looks like I need to use EndOfRowset but I do not know how to use it for sure.

If this correct can someone show me a code example and if I am incorrect can someone tell me how to do this?

Thanks

View 19 Replies View Related

Problem In SQL Query Writting For Cube Metadata

Aug 24, 2006

Hi Friends,
I am trying to write SQL statement for getting information about Cube metadata.
When we create any table in MSSQL server, we can trace out its information from system tables in master database by querying tables like sysobjects, syscolumns etc.
Like that I have created a cube using MS Analysis services and I can see Metadata (like Creation Date, Processed on etc) on 'Metadata' tab of cube. But I want to access its contents by writting SQL statement. For this I could not locate any system level table where this information gets stored.
Could any one help me for writting htis system table level query for accessing metadata info of cube?

Thanks in advance.
Avadhoot

View 3 Replies View Related

Problem With Writting A Report (SQL Slow Running)

Jul 20, 2005

HiI am trying to write a report that calculates the average number of salesover 7, 14, 31 and 365 days for each hourly period of the day. the problemis it takes over 4 minutes to run.e.g.Average Xactions per Hour7 Days 14 Days 31 Days 365 Days00:00 - 01:00 1,141.6 579.2 261.6 28.801:00 - 02:00 1,298.0 649.6 293.4 30.0The report was use to be purely ASP running SQL Statements.I then changed it to ASP Running a SP 24 times - this reduced running timeby about 1 minute.I then changed it so that the stored proc looped internally 24 times andreturns the data.I have ran the Index Tuning Wizard on the SQL and Implemented the indexessuggested - this actually increase execution time by 20 seconds.Below is the stored procedure I am currently using that loops internally 24times and returns the data.Can anyone suggest a better way / any improvements I could make ?Many ThanksSteve-----------------------------------------------------------------------------------------------------CREATE procedure ams_RPT_Gen_Stats@strResult varchar(8) = 'Failure' output,@strErrorDesc varchar(512) = 'SP Not Executed' output,@strTest varchar(1),@strCurrency varchar(3),@strVFEID varchar(16)asdeclare @strStep varchar(32)set @strStep = 'Start of Stored Proc'/* start insert sp code here */create table ##Averages (TheHour varchar(2),Day7Avge float ,Day14Avge float ,Day31Avge float ,Day365Avge float)declare @numHour varchar(2)declare @strSQL varchar(2000)declare @Wholesalers varchar(64)declare MyHours cursor FORWARD_ONLY READ_ONLY forselect convert(char(2), timestamp,14) as TheHourfrom xactionsgroup by convert(char(2), timestamp,14)order by convert(char(2), timestamp,14)if @strTest = 'Y'select @Wholesalers = VALUE FROM BUSINESSRULES WHERE NAME ='TEST_Wholesalers'open MyHoursfetch next from MyHours into @numHourwhile @@fetch_status = 0beginset @strSQL = 'insert into ##Averages (TheHour, Day7Avge) ( select ''' +@numHour + ''', ' +'count(*) / 7.00 ' +'FROM ' +'XACTIONS INNER JOIN ' +'RETAILER ON XACTIONS.RETAILERID = RETAILER.RETAILERID ' +'WHERE ' +'(DATEDIFF(DAY , xactions.timestamp , GETDATE() ) < 8) and ' +'xactions.xactiontotal <> 0 and ' +' convert(char(2) , timestamp, 14) = ''' + @numHour + ''' 'if @strTest = 'Y'set @strSQL = @strSQL + ' and retailer.BillOrgID not in (' +@Wholesalers + ') 'if @strCurrency <> '*'set @strSQL = @strSQL + ' and xactions.XACTIONCURRENCY = ''' +@strCurrency + ''' 'if @strVFEID <> '*'set @strSQL = @strSQL + ' and xactions.VFEID = ''' + @strVFEID + ''''set @strSQL = @strSQL + ')'exec ( @strSQL )set @strSQL = 'update ##Averages set Day14Avge = ( select ' +'count(*) / 14.00 ' +'FROM ' +'XACTIONS INNER JOIN ' +'RETAILER ON XACTIONS.RETAILERID = RETAILER.RETAILERID ' +'WHERE ' +'(DATEDIFF(DAY , xactions.timestamp , GETDATE() ) < 15) and ' +'xactions.xactiontotal <> 0 and ' +' convert(char(2) , timestamp, 14) = ''' + @numHour + ''' 'if @strTest = 'Y'set @strSQL = @strSQL + ' and retailer.BillOrgID not in (' +@Wholesalers + ') 'if @strCurrency <> '*'set @strSQL = @strSQL + ' and xactions.XACTIONCURRENCY = ''' +@strCurrency + ''' 'if @strVFEID <> '*'set @strSQL = @strSQL + ' and xactions.VFEID = ''' + @strVFEID + ''' 'set @strSQL = @strSQL + ') where TheHour = ''' + @numHour + ''' 'exec ( @strSQL )set @strSQL = 'update ##Averages set Day31Avge = ( select ' +'count(*) / 31.00 ' +'FROM ' +'XACTIONS INNER JOIN ' +'RETAILER ON XACTIONS.RETAILERID = RETAILER.RETAILERID ' +'WHERE ' +'(DATEDIFF(DAY , xactions.timestamp , GETDATE() ) < 32) and ' +'xactions.xactiontotal <> 0 and ' +' convert(char(2) , timestamp, 14) = ''' + @numHour + ''' 'if @strTest = 'Y'set @strSQL = @strSQL + ' and retailer.BillOrgID not in (' +@Wholesalers + ') 'if @strCurrency <> '*'set @strSQL = @strSQL + ' and xactions.XACTIONCURRENCY = ''' +@strCurrency + ''' 'if @strVFEID <> '*'set @strSQL = @strSQL + ' and xactions.VFEID = ''' + @strVFEID + ''' 'set @strSQL = @strSQL + ' ) where TheHour = ''' + @numHour + ''' 'exec ( @strSQL )set @strSQL = 'update ##Averages set Day365Avge = ( select ' +'count(*) / 365.00 ' +'FROM ' +'XACTIONS INNER JOIN ' +'RETAILER ON XACTIONS.RETAILERID = RETAILER.RETAILERID ' +'WHERE ' +'(DATEDIFF(DAY , xactions.timestamp , GETDATE() ) < 366) and ' +'xactions.xactiontotal <> 0 and ' +' convert(char(2) , timestamp, 14) = ''' + @numHour + ''' 'if @strTest = 'Y'set @strSQL = @strSQL + ' and retailer.BillOrgID not in (' +@Wholesalers + ') 'if @strCurrency <> '*'set @strSQL = @strSQL + ' and xactions.XACTIONCURRENCY = ''' +@strCurrency + ''' 'if @strVFEID <> '*'set @strSQL = @strSQL + ' and xactions.VFEID = ''' + @strVFEID + ''' 'set @strSQL = @strSQL + ' ) where TheHour = ''' + @numHour + ''' 'exec ( @strSQL )fetch next from MyHours into @numHourend -- while fetchclose MyHoursdeallocate MyHoursselect * from ##Averages order by TheHourdrop table ##Averages/* end insert sp code here */if (@@error <> 0)beginset @strResult = 'Failure'set @strErrorDesc = 'Fail @ Step :' + @strStep + ' Error : ' +CONVERT(VARCHAR,@@Error)return -1969endelsebeginset @strResult = 'Success'set @strErrorDesc = ''endreturn 0GO

View 1 Replies View Related

The OLE DB Provider MSDAORA For Linked Server .... Does Not Contain The Table COUNTRY. The Table Either Does Not Exist Or The Current User Does Not Have Permissions On That Table.

Jun 13, 2006

I am using SQL Server 2005 and trying to create a linked server on Oracle 10. I used the commands below:
EXEC sp_addlinkedserver
@server = 'test1',
@srvproduct = 'Oracle',
@provider = 'MSDAORA',
@datasrc = 'testsource'
exec sp_addlinkedsrvlogin
@rmtsrvname = 'test1',
@useself = 'false',
@rmtuser='sp',
@rmtpassword='sp'
 
When I execute
select * from test1...COUNTRY
I get the error. "The OLE DB provider "MSDAORA" for linked server "...." does not contain the table "COUNTRY". The table either does not exist or the current user does not have permissions on that table."
The 'sp' user I am connecting is the owner of the table. What could be the problem ?
Thanks a lot.

View 3 Replies View Related

I Have Created A Table Table With Name As Varchar And Id As Int. Now I Have Started Inserting The Rows Like, Insert Into Table Values ('arun',20).

Jan 31, 2008

I have created a table Table with name as Varchar and id as int. Now i have started inserting the rows like, insert into Table values ('arun',20).Yes i have inserted a row in the table. Now i have got the values " arun's ", 50.                 insert into Table values('arun's',20)  My sqlserver is giving me an error instead of inserting the row. How will you solve this problem? 
 

View 3 Replies View Related

Moving From One Table To Other Table Automatically For Every 3 Months By Checking The Paticular Value Of The Table Field

Mar 29, 2007

Hi
 
I am having a table called as status ,in that table one field is there i.e. currentstatus.
the rows which are having currentstatus as "ticket closed",i want to move those rows into  other table called repository which is having same table structure as status table.
I can do programatically.
but is there any way for every 3 months system has to check and do this action means moving to repository table automatically?
 
Please help me.
 
Thanks.

View 1 Replies View Related

SQL Server 2008 :: Insert From Table 1 To Table 2 Only If Record Doesn't Exist In Table 2?

Jul 24, 2015

I'm inserting from TempAccrual to VacationAccrual . It works nicely, however if I run this script again it will insert the same values again in VacationAccrual. How do I block that? IF there is a small change in one of the column in TempAccrual then allow insert. Here is my query

INSERT INTO vacationaccrual
(empno,
accrued_vacation,
accrued_sick_effective_date,
accrued_sick,
import_date)

[Code] ....

View 4 Replies View Related

Default Table Owner Using CREATE TABLE, INSERT, SELECT && DROP TABLE

Nov 21, 2006

For reasons that are not relevant (though I explain them below *), Iwant, for all my users whatever privelige level, an SP which createsand inserts into a temporary table and then another SP which reads anddrops the same temporary table.My users are not able to create dbo tables (eg dbo.tblTest), but arepermitted to create tables under their own user (eg MyUser.tblTest). Ihave found that I can achieve my aim by using code like this . . .SET @SQL = 'CREATE TABLE ' + @MyUserName + '.' + 'tblTest(tstIDDATETIME)'EXEC (@SQL)SET @SQL = 'INSERT INTO ' + @MyUserName + '.' + 'tblTest(tstID) VALUES(GETDATE())'EXEC (@SQL)This becomes exceptionally cumbersome for the complex INSERT & SELECTcode. I'm looking for a simpler way.Simplified down, I am looking for something like this . . .CREATE PROCEDURE dbo.TestInsert ASCREATE TABLE tblTest(tstID DATETIME)INSERT INTO tblTest(tstID) VALUES(GETDATE())GOCREATE PROCEDURE dbo.TestSelect ASSELECT * FROM tblTestDROP TABLE tblTestIn the above example, if the SPs are owned by dbo (as above), CREATETABLE & DROP TABLE use MyUser.tblTest while INSERT & SELECT usedbo.tblTest.If the SPs are owned by the user (eg MyUser.TestInsert), it workscorrectly (MyUser.tblTest is used throughout) but I would have to havea pair of SPs for each user.* I have MS Access ADP front end linked to a SQL Server database. Forreports with complex datasets, it times out. Therefore it suit mypurposes to create a temporary table first and then to open the reportbased on that temporary table.

View 6 Replies View Related

Dbo.Table Of A Database In The .SQLEXPRESS Object Explorer: How To Copy The Dbo.Table To The Another Blank Dbo.Table?

Jan 9, 2008

Hi all,

The following dbo.Tables of Northwind.mdf in my .SQLEXPRESS (SQL Server Management Studio Express) are missing:
dbo.Categories
dbo.CustomerCustomerDemo
dbo.CustomerDemographics
dbo.Customers
dbo.Employees
dbo.EmployeeTerritories
dbo.Order Details
dbo.Orders
dbo.Products
dbo.Regions
dbo.Shippers
dbo.Suppliers
dbo.Territories.

But, I have these dbo.Tables in a different Database "xyzDatabase". How can I copy each of these dbo.Tables to the another blank dbo.Table of Northwind Database?

I right clicked on the dbo.Categories and I saw the following thing:
dbo.Categories
New Table...
Modify
Open Table
Script Table as |> CREATYE To |>
DROP To |>
SELECT To |>
INSERT To |> New Query Editor Window
File....
Clipboard
UPDATE To |>
DELETE to |>
From the above observation,I think it is possible to copy the dbo.Table from the one Database to the Northwind Database that needs to be repaired. Please help and advise me how to do this task or tell me where I can find the Microsoft document that gives the details of this X-copy thing.

Thanks in advance,
Scott Chang

P. S. I am using VB 2005 Express to create a project to learn "Calling Stored Procedures with ADO.NET" (see Paul Kimmel's article in http://www.developer.com/db/article.php/3438221) that needs the dbo.Tables of Northwind Database and my Northwind Database has been screwed up for quite a while and needs a big repair.

View 3 Replies View Related

What Is The Difference Between: A Table Create Using Table Variable And Using # Temporary Table In Stored Procedure

Aug 29, 2007

which is more efficient...which takes less memory...how is the memory allocation done for both the types.

View 1 Replies View Related

Delete Table And Immediately Crate Table, Error Occur Table Already Exist

May 29, 2008

'****************************************************************************

Cmd.CommandText = "Drop Table Raj"



Cmd.ExecuteNonQuery()


Cmd.CommandText = "Select * Into Raj From XXX"



Cmd.ExecuteNonQuery()

'**************************************************************************



This generates error that Table already exist.

If Wait 1 sec then execute statement then it works fine.



Thanks in Advance

Piyush Verma

View 1 Replies View Related

How To Search Multiple Table Which Table Name Is Store In Another Table And Join The Result Together?

Dec 1, 2006

I have one control table to store all related table name
 Table ID                   TableName
     1                           TableA
     2                           TableB
 
In Table A:
RecordID                Value
     1                         1
     2                         2
     3                         3
 
In Table B:
RecordID             Value
    1                         1
    2                         2
    3                         3
 How can I get the result by select the Table list first and then combine the data in table A and table B?
 
Thank you!

View 1 Replies View Related

Stored Procedure To Copy Table 1 To Table 2 Appending The Data To Table 2.

Jan 26, 2006

Just wondering if there is an easy transact statement to copy table 1 to table 2, appending the data in table 2.with SQL2000, thanks.

View 2 Replies View Related

Newbie-DELETE A Record In A Table A That Is Related To Table B, And Table B Related To Table A

Mar 20, 2008

Hi thanks for looking at my question

Using sqlServer management studio 2005

My Tables are something like 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?

Thanks

View 8 Replies View Related

Is A Temp Table Or A Table Variable Used In UDF's Returning A Table?

Sep 17, 2007

In a table-valued UDF, does the UDF use a table variable or a temp table to form the resultset returned?
 

View 1 Replies View Related

Difference In Creating Temporary Table By #table And ##table

Nov 29, 2006

Banti writes "IF i create temporary table by using #table and ##table then what is the difference. i found no difference.
pls reply.
first:
create table ##temp
(
name varchar(25),
roll int
)
insert into ##temp values('banti',1)
select * from ##temp
second:
create table #temp
(
name varchar(25),
roll int
)
insert into #temp values('banti',1)
select * from #temp

both works fine , then what is the difference
waiting for ur reply
Banti"

View 1 Replies View Related

T-SQL (SS2K8) :: Date Comparison In Two Table By Returning Nearest Date Of Table A In Table B

Jun 9, 2014

I am having a problem in creating query for this exciting scenario.

Table A

ID ItemQtyCreatedDatetime
W001 CB112014-06-03 20:30:48.000
W002 CB112014-06-04 01:30:48.000

Table B

IDItemQtyCreatedDatetime
A001 CB112014-06-03 19:05:48.000
A002 CB112014-06-03 20:05:48.000
A003 CB112014-06-03 21:05:48.000
A004 CB112014-06-04 01:05:48.000
A005 CB112014-06-04 02:05:48.000

I would like to return the nearest date of Table B in my table like for

ID W001 in table B should return ID A002 CreatedDatetime: 2014-06-03 20:05:48.000
ID W002 in table B should return ID A004 CreatedDatetime: 2014-06-04 01:05:48.000

View 3 Replies View Related

How To Create A System Type Table/ Change User Table To System Table.

May 23, 2007

Is there any Posibility to change a User Table to System Table.

How to create one system table.

I am in Big mess that One of the Table I am using is in System Type.

I cant Index the same. Is there any Mistake we can change a user table to system table.....

View 9 Replies View Related

How Do I Enter NULL In A Table Cell In The Enterprise Manager UI For Table Data Entry?

Sep 9, 2005

I have a column defined as smalldatetime. Default length (4), and "allow NULLS" is checked.In the Enterprise Manager UI, when i enter data into that table row, if i just tab past that column, all is well, and the value is represented in the UI as <NULL>.The problem comes once i ever enter a date into that column.  Say i have entered a date (all is well), and now i want to remove that entry and go back to NULL (after the date value has been committed, different entry session, say).How is that done?It seems to me, once a date has ever been entered into that column, now, if i try to remove it, i get the error "The value you entered is not consistant with the data type or length of the column, or over grid buffer limit".  I have tried deleting the value, entering spaces, entering the string NULL or the string <NULL>; maybe some other tries as well, but none works, i always get that error message and am not allowed to proceed past that cell until i restore a date value to it.  I want to get back to <NULL>.Anybody know?Thank you.Tom

View 1 Replies View Related

Transpose Source Data From A System Via Metadata Lookup Table Into Destination Table

Apr 1, 2014

I am stuck on finding a solution to transpose source data from a system via a metadata look-up table into a destination table. I need a method to transpose/pivot the source data into columns (which are by various data-types). The datatypes for each column are listed in a metadata table.

Source Data Table:

Table Name: Source

SrcID AGE City Date
01 32 London 01-01-2013
02 35 Lagos 02-01-2013
03 36 NY 03-01-2013

Metadata Table:

Table Name:Metadata

MetaID Column_Name Column_type
11 AGE col_integer
22 City col_character
33 Date col_date

Destination table:

The source data to be loaded into the destination table(as shown below):

Table Name: Destination

SrcID MetaID col_int col_char col_date
01 11 32 - -
01 22 - London -
01 33 - - 01-01-2013
02 11 35 - -
02 22 - Lagos -
02 33 - - 02-01-2013
03 11 36 - -
03 22 - NY -
03 33 - - 03-01-2013

View 7 Replies View Related

SQL Server 2012 :: Compare Two Table Data And Insert Changed Field To Third Table

Aug 12, 2014

I want Compare two Table data and insert changed field to the third table ...

View 9 Replies View Related

SQL Server 2012 :: Stored Procedures Compiles Even When There Is No CREATE TABLE For A Temp Table

Feb 11, 2015

i am inserting something into the temp table even without creating it before. But this does not give any compilation error. Only when I want to execute the stored procedure I get the error message that there is an invalid temp table. Should this not result in a compilation error rather during the execution time.?

--create the procedure and insert into the temp table without creating it.
--no compilation error.
CREATE PROC testTemp
AS
BEGIN
INSERT INTO #tmp(dt)
SELECT GETDATE()
END

only on calling the proc does this give an execution error

View 3 Replies View Related

SQL Server 2008 :: Capture Sessions Which Modify A Table With Details Modified In Table?

Apr 10, 2015

I created am inventory table with few columns say, Servername, version, patching details, etc

I want a tracking of the table.

Let's say people are asked to modify the base table and I want a complete capture of the details modified and the session of the user ( ) who (system_user) is actually modifying the details.

View 1 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved