Hello all,Number of rows in a table was increased significantly. Is there a way to seewhether data was inserted in to the table, or whether data was appended tothe table?Thanks in advance,Do.--Message posted via http://www.sqlmonster.com
I deliberately intend to add some duplicates to one of my tables. For eg
Job User IsAdmin
JobID 235User ID 1 JobID 235User ID 5 JobID 235User ID 9 JobID 235User ID 5 JobID 235User ID 2 JobID 235User ID 9 JobID 235User ID 10 JobID 235User ID 1
I know its bad practice to do such a thing but there is a genuine reason. What I need to do is to be able to have a SQL statement that appends true to the IsAdmin field whenever it encounters the next UserID thats happens to be a duplicate. Hence the above would look like:
Job User IsAdmin
JobID 235User ID 1 JobID 235User ID 5 JobID 235User ID 9 JobID 235User ID 5 True JobID 235User ID 2 JobID 235User ID 9 True JobID 235User ID 10 JobID 235User ID 1 True
I'm completely stuck in here. I have two tables, for simplicity i'll call them tbl_X and tbl_Y and i'll call the unique key Ukey
I need to create a stored procedure that must be run daily on a scheduled time. When executed, it must compare these two tables and insert rows from tbl_X into tbl_Y when a row exists in tbl_Y but not in tbl_X.
The following code returns the rows that are in tbl_Y, but not in tbl_X: ---------- SELECT Ukey FROM tbl_X WHERE NOT EXISTS (SELECT Ukey FROM tbl_Y WHERE tbl_Y.Ukey = tbl_X.Ukey) ----------
But....how do i insert these rows into tbl_X ? I've tried to declare the tbl_Y.Ukey and use that to do an INSERT statement, but that didn't work out.
Basically, I need to insert the wbs2 and wbs3 where it does not exist in each wbs1.
What I have now will find the values that need to be inserted for a particular project but I don't know how to go through each project and perform the insert:
Select * from PR_template Where Not Exists (Select Wbs1, Wbs2, Wbs3 from PR where PR.WBS2 = PR_Template.WBS2 And PR.WBS3 = PR_Template.Wbs3 and pr.wbs1 = '123-456') Order by wbs2, wbs3 asc
How do I Use the insert code below only if a record does not exist in the cisect table? Then if it exists I just want to
update cisect set ml_desc_0 = cus_type_desc from artypfil_sql A join cisect c on a.cus_type_cd = c.sct_code INSERT INTO [002].[dbo].[cisect] ([sct_code] ,[ml_desc_0] ,[syscreated] ,[syscreator]
I've got an access table with about 2 million rows. I'm using this to update a table in SQL that holds pretty much the exact same data, only with an added Identity column.
From week to week, the access table grows. For example, next week it may have 2.1 millions rows, the week after 2.2 million, etc.
The goal of the DTS is to keep the SQL table up to date w/ the access one. In the past, this has been done by deleting everything from the SQL Table and then importing the ENTIRE access table. This not only takes more time then need be, since the majority of the records *already* existed, but it also threw referential integrity out the door - other tables should be referencing the Identity in the SQL Table. IDEALLY, the only rows that would be transferred from the access file are ones that don't already exist in the SQL table.
I don't want to re-invent the wheel, and have to confess being a little under-schooled on all that SSIS has to offer. Is there a Data Flow Transformation that would solve this?? Any other advice? If all else fails, I'd probably just dump the entire access table to a temp table and then insert vals into the production table that don't exist, but even this would require more temp hard drive space then I'd like.
i need to write a query that insert in A table if and only if the row does not exist already in the table (the source is a select statement). i tried the following:
insert into [A] select * from [B] where Not EXISTS (select * from [A])
table [A] is still empty, but it does not insert any thing! .. what i know is that the EXIST checks if the selected row exists in the subquery, ain't ?
Someone help me out .How to solve the problem.I built a stored procedure in MS SQL 2005 to bulk insert into a table by reading the .txt file. But my stored procedure throws an error. "Could not bulk insert. File ' @PathFileName ' does not exist." My stored given below :- CREATE PROCEDURE [dbo].[ps_CSV_Import] AS DECLARE @PathFileName varchar(2000) ----Step 1: Build Valid BULK INSERT Statement DECLARE @SQL varchar(2000) SELECT @PathFileName="D:Areazone.txt" BEGIN SET @SQL = "BULK INSERT Temp FROM '"+" @PathFileName "+"' WITH (FIELDTERMINATOR = '"",""') " END --Step 2: Execute BULK INSERT statement EXEC (@SQL) --Step 3: INSERT data into final table INSERT mstArea(Description,Refid) SELECT SUBSTRING(Description,2,DATALENGTH(Description)-1), SUBSTRING(RefId,1,DATALENGTH(RefId)-0) FROM Temp --Step 4: Empty temporary table TRUNCATE TABLE Temp Please help me ,if someone have any solution
Im using a store proc in SQL server.I use one table to store my hockey statistics data of each player in the league.When i submit my form i would like to check if there is any sheet of that player that allready exist .. If so then i do update.. if it does not exist i do the insert statement.Here the way i figured it out ! One store proc to do the work of the insert or update. And one to check if the player exist in the statistics table. But i just cant find a way to return a good value from my second store proc. Does my logic make sence ? any ideas ?thank you<code>create procedure Hockey_Player_UpdateForwardStatistics @LeagueID int, @GamePlayerID int, @Games int as declare @PlayerID int @PlayerID = Hockey_CheckPlayerStatistics(@LeagueID, @GamePlayerID) if @PlayerID = 0begininsert into Hockey_PlayerStatistics( Games)values( @Games)end ELSE beginupdate Hockey_PlayerStatistics set Games = @Gameswhere LeagueID = @LeagueID and PlayerID = @PlayerIDend</code>
Hi guys,i have a little problem here.im attempting to write a stored procedure that compares two tables ofthe same data structure and adds (inserts) extra records that exist intable1 to table2.My problem is that i dont have a unique identifier between the tables.i think someone said that i needed to build up a keyany ideas greatly appreciated ??C
Someone help me out .How to solve the problem.I built a stored procedure in MS SQL 2005 to bulk insert into a table by reading the .txt file. But my stored procedure throws an error."Could not bulk insert. File ' @PathFileName ' does not exist."My stored given below :-CREATE PROCEDURE [dbo].[ps_CSV_Import]AS DECLARE @PathFileName varchar(2000) ----Step 1: Build Valid BULK INSERT Statement DECLARE @SQL varchar(2000) SELECT @PathFileName="D:Areazone.txt" BEGIN SET @SQL = "BULK INSERT Temp FROM '"+" @PathFileName "+"' WITH (FIELDTERMINATOR = '"",""') " END--Step 2: Execute BULK INSERT statementEXEC (@SQL)--Step 3: INSERT data into final tableINSERT mstArea(Description,Refid)SELECT SUBSTRING(Description,2,DATALENGTH(Description)-1), SUBSTRING(RefId,1,DATALENGTH(RefId)-0) FROM Temp--Step 4: Empty temporary tableTRUNCATE TABLE TempPlease help me ,if someone have any solution
help on CREATE stored procedure delete and after insert where not exist in one stored procedure in table_B
Code Snippet CREATE PROCEDURE [dbo].[delete_from_table_B] @empID varchar(500) as DELETE FROM table_B WHERE charindex(','+CONVERT(varchar,[empID])+',',','+@empID+',') > 0
---HELP from this ponit how to insert ? after where not exist
IF @@ROWCOUNT > 0
BEGIN
insert into table_B set (empID,ShiftDate,shiftType) where not exist
I am trying to bulk insert a text file into SQL 2005 table. When I execute the bulk insert I get the error
"Msg 4860, Level 16, State 1, Line 1. Cannot bulk load. The file "\ENDUSER-SQLEnduserTextB1020063.txt" does not exist."
The text file that it is saying does not exist I recently created thru my code. I can open the file but only when I rename the file will the Bulk Insert work. After creating the text file I am moving it to the server that SQL server is running on. Also if I run sp_FileExists it also says the file does not exist unless again I rename the file then this stored procedure recognizes the file. I dont' know if I have a permission issue or what is the problem. Any help would be appreiated.
All, Using access 2003 frontend and sql server 2008 backend. I have an append query to insert 80000 from one table to an empty table. I get an error:
"Microsoft Office Access set 0 field(s) to Null due to a type conversion failure, and didn't add 36000 record(s) to the table due to key violations, 0 record(s) due to lock violations, and 0 record(s) due to validation rule violations."
I know this error normally comes if there are dups in a field that doesnt allow.
I am using INSERT into Vendors (.....) VALUES (....) form of insert statement. How can I make sure that the insert fails if thie new vendor's vendorname exists? I cannot create a unique index on 'VendorName' column since it is more than 900 bytes and SQL Server will not allow to create index on a column bigger than 900 bytes.
Can I delete the record if it exist before we do an insert at the DataFlow level base on a key of the record we are working on? Basically we want to keep history records and delete and reinsert any records that exist in the table.
My colleague is working on bulk insert task from SSIS and since the data file does not contain any valid delimeter one of the suggestion he got is to use a file format to address the issue. Thus a bcp command is used to generate the format file, as per below.
The file file format was generated, from the data flow we added the BULK INSERT task and set the properties accordingly including the File Format and location of the file. Upon running the task itself we encountered the error as per below.
[Bulk Insert Task] Error: An error occurred with the following error message: "Cannot bulk load. The file "C:HFISTAT.fmt" does not exist.".
Progress: The Bulk Insert task is completed. - 100 percent complete
Task Bulk Insert Task failed
Have checked the file and it is in C: drive and it is not protected or read-only. Validated the output file and it is as per expected. Any help would be appreciated very much.
i have the following code in visual studio 2005 using VB it is running an insert query - this works fine but i want to know how can i get the primaty key value(which is auto generated) of the row that i just inserted...
Dim conn As New SqlConnection(My.Settings.connStr)
After executing an INSERT, I would like to retrieve the primary key of the last row inserted. I've tried running SELECT @@IDENTITY in a query, but I get an OleDbException with the message: {"Syntax error. in query expression 'SELECT @@IDENTITY'."}. does anyone know what to do?
Hi,I've got a stored procedure that's inserting data into a sql database fine. The only problem is that I'm not sure how to read back the value of the auto increment field that was just generated by the insert (e.g the id field). Any help appreciated.
Hi I have a table in sql server with a numeric field as Primary Key. When i insert a new record i need that primary key increments automatic (like access auto increment) because i want avoid the possibility of duplicate Primary Keys. Is that possible? Thank you
I am using the bulk insert statement below to import data from a csv and excel files. As I am running 64bit versions of windows, and could not find any sql import statements.
However I noticed it does not allow any primary key, hence after importing to the temp table, I then import in sql to the main table.Is there anyway to fix the temp table ? ie add a PK value
BULK INSERT CSV_TESTING FROM 'd:MAM-NAP.csv' WITH ( FIELDTERMINATOR = ',', ROWTERMINATOR = ' )
I am new to SSIS and still trying to design my first package. My package doesn't seem to want to complete when I have set an indentity field with an identity seed in my table as a primary key.
If the field is not a primary key, the package runs fine.
Any ideas how to insert records when there is a primary key in the table?
In another instance, I am actually trying to fill the primary key with a value from flat file and that also does not work.
Hi,newbie question. I have an plain INSERT INTO clause:BEGIN TRANINSERT INTO BILLSSELECTBillCode,MyUNIDFROM DPA_BILLSWHERE ErrorCode IS NULLCOMMIT TRANThe original DPA_BILLS table can hold (and actually holds) rows withnon-unique values of BillCode, which is primary key in the destinationBILLS table. An acceptable behaviour would be to update the existingrow. Given that these constraints have to be kept, which is the bestway to act? Shall I process in advance my source table, resolvingforeing key conflicts, or shall I rely on some error handling in theINSERT clause?Thanx
Ive added a primary key called ID to my table, now my insert stored procedure dont no longer work.
i want an unique identifier for each row.
heres my stored procedure:
CREATE PROCEDURE composeMessage -- Add the parameters for the stored procedure here @username varchar(24), @sender varchar(24), @date dateTime, @subject varchar(255), @message varchar(2500)
AS BEGIN
insert into Messages( "Username", "Sender", "Date", "Subject", "Message" ) values ( @username, @sender, @date, @subject, @message ) END GO
heres my sqlcreate table:
USE [Messenger] GO /****** Object: Table [dbo].[Messages] Script Date: 09/12/2006 15:13:52 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_PADDING ON GO CREATE TABLE [dbo].[Messages]( [Username] [varchar](24) COLLATE Latin1_General_CI_AS NOT NULL, [Sender] [varchar](24) COLLATE Latin1_General_CI_AS NOT NULL, [Subject] [varchar](255) COLLATE Latin1_General_CI_AS NOT NULL, [Message] [varchar](2500) COLLATE Latin1_General_CI_AS NOT NULL, [Date] [datetime] NOT NULL, [ID] [int] NOT NULL, CONSTRAINT [PK_Messages] PRIMARY KEY CLUSTERED ( [ID] ASC )WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY] ) ON [PRIMARY] GO SET ANSI_PADDING OFF
As primary keycan't be null, what do i put for primary key for my insert to work?
I would like to insert into a table with a primary key that has a uniqueidentifier. I would like it to go up by one each time I execute this insert statement. It would be used as my ReportId My VB code is this. Protected Sub btncreate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btncreate.Click 'set connection string Dim errstr As String = "" Dim conn = New SqlConnection("Data Source=.SQLEXPRESS;AttachDbFilename=|DataDirectory|ASPNETDB.MDF;Integrated Security=True;User Instance=True") 'set parameters for SP Dim cmdcommand = New SqlCommand("sprocInsertNewReport", conn) cmdcommand.commandtype = CommandType.StoredProcedure cmdcommand.parameters.add("@UserName", Session("UserName")) cmdcommand.parameters.add("@Week", vbNull) cmdcommand.parameters.add("@Date", vbDate) cmdcommand.parameters.add("@StartTime", vbNull) cmdcommand.parameters.add("@EndTime", vbNull) cmdcommand.parameters.add("@HeatTicket", vbNull) cmdcommand.parameters.add("@Description", vbNull) cmdcommand.parameters.add("@TakenAs", vbNull) cmdcommand.parameters.add("@Dinner", vbNull) cmdcommand.parameters.add("@Hours", vbNull) cmdcommand.parameters.add("@Rate", vbNull) cmdcommand.parameters.add("@PayPeriod", vbNull) cmdcommand.parameters.add("@LastSave", vbNull) cmdcommand.parameters.add("@Submitted", vbNull) cmdcommand.parameters.add("@Approved", vbNull) cmdcommand.parameters.add("@PagerDays", vbNull) cmdcommand.parameters.add("@ReportEnd", vbNull) Try 'open connection here conn.Open() 'Execute stored proc cmdcommand.ExecuteNonQuery() Catch ex As Exception errstr = "" 'An exception occured during processing. 'Print message to log file. errstr = "Exception: " & ex.Message Finally 'close the connection immediately conn.Close() End Try If errstr = "" Then Server.Transfer("TimeSheetEntry.aspx") End If My SP looks like this ALTER PROCEDURE sprocInsertNewReport