Here is the steps I should take...
1- Check for the log table and find run status ( there is a date field which tells the day run)
2- Lets say last day was 2008-05-15, So I have to check A1.DDDDMMYYY file exists in the folder for each
day like A1.20080516,A1.20080517 and A1.20060518 ( until today)
3- if A1.20080516 text file exist then I have to move it to the table and same thing for other dates
like if A1.20080517 exists I have to load it to table and so on
it looks like for each loop, first I have to get the last date and then I have to check the file exists for each date and
if the date file exists then I have to load it into table...
Please tell me How can I do it. it looks complex looping...
Hi, I'm importing 10 csv files with a different name daily. If the file does not exists in a directory (which I have in variable) I want to write an error message, if it does I want to proceed to the for each loop. How do I do this? Any suggestions?
I need to find out if a Transaction ID exists in Table A that does not exist in Table B. Â If that is the case, then I need to insert into Table B all of the Transaction IDs and Descriptions that are not already in. Seems to me this would involve If Not Exists and then an insert into Table B. Â This would work easily if there were only one row. Â What is the best way to handle it if there are a bunch of rows? Â Should there be some type of looping?
Hello,Using Enterprise Manager, I deleted from my database the only tablethat contained records (Right-Click on Table, Choose "Delete Table").My expectation was that the LARGE .mdf file would be reduced to minimalsize (at least as small as the Northwind MDF). However, it's still 4+Gig in size!! (Northwind is 2.62 MB). This is a problem, bc I deletedthe table in order to recapture hard drive space.NOTE: I already tried using Shrink Database in EM. This significantlyreduced the size of the .mdf file from its original (i.e. pre-delete)size of 38 Gig to present size of 4 Gig.What can I do to further reduce the size of the MDF file?Thank you.
I am getting info from one table, CalibrationReview, that is not inanother table, tblEquipments. SELECT EquipmentNumber, Model, SerialNumber, Make, CalLabName, CalDateFROM CalibrationReviewWHERE NOT EXISTS (SELECT AssignedID FROM tblEquipments WHERE AssignedID = CalibrationReview.EquipmentNumber) Now, I need to take these rows and INSERT them into tblEquipments,but with some conditions. tblEquipments has some contraints, so, the following needs to be done: Using dbo.CalibrationReview.EquipmentNumber, get CalibrationMaster.TestTechnology where dbo.CalibrationReview.EquipmentNumber = dbo.CalibrationMaster.EquipmentID Then take CalibrationMaster.TestTechnology and read tblTestTechnology.testTechnology and get tblTestTechnology.id So, tblEquipments.testTechnology = tblTestTechnology.id OR 1 if not foundWHERE dbo.CalibrationReview.EquipmentNumber = dbo.CalibrationMaster.EquipmentID and CalibrationMaster.TestTechnology = tblTestTechnology.testTechnology And similar for CalibrationReview.CalLabName. tblEquipments.calLab = tblLabs.ID where tblLabs.LabName = CalibrationReview.CalLabName I hope this is clear as I can write this in code behind, but it'smuch better using sql simply because it's faster and only needs tobe run once. Inheriting databases and combining all of them to develop a large.Net management system is fun, huh? Thanks for any input, Zath
SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_PADDING ON GO CREATE TABLE [dbo].[PaymentsLog](
[Code] ....
Is there a way to look at the DatePeriod table and use the StartDtae and EndDate as the periods to be used in the select statement and then cursor through each date between these two dates and then insert the data in to the PaymentsLog table?
INPUT: A table contains 2 columns with data i need. column A=Filename and column B=FileContent
PROCESS: I need to loop through ea record in the table and retrieve columns A and B. Then for ea column i need to write the Content hold in column B into File hold in column A.
I so far found out, that i need a Execute SQL Task in Control Flow querying the table and get columns A and B into 2 variables, plus a 3rd var holding the object. Then the output goes into a Foreach Loop Container. From this point i don't know how to continue. I tried to put a Data Flow Task inside the Foreach Loop, but couldn't find out how i now get the 2 variables to the Data Flow Task and use them to for the file to be written and the content to be placed in the file.
Is there any example similiar to that so i could learn how to start on that?
This is on Sybase but I'm guessing that the same situation would happen on SQL Server. (Please confirm if you know).
I'm looking at these new databases and I'm seeing code similar to this all over the place:
if not exists (select 1 from dbo.t1 where f1 = @p1) begin select @errno = @errno | 1 end
There's a unique clustered in dex on t1.f1.
The execution plan shows this for this statement:
FROM TABLE dbo.t1 EXISTS TABLE : nested iteration. Table Scan. Forward scan. Positioning at start of table.
It's not using my index!!!!!
It seems to be the case with EXISTS statements. Can anybody confirm?
I also hinted to use the index but it still didn't use it.
If the existence check really doesn't use the index, what's a good code alternative to this check?
I did this and it's working great but I wonder if there's a better alternative. I don't really like doing the SET ROWCOUNT 1 and then SET ROWCOUNT 0 thing. SELECT TOP 1 won't work on Sybase, :-(.
SET ROWCOUNT 1 SELECT @cnt = (SELECT 1 FROM dbo.t1 (index ix01) WHERE f1 = @p1 ) SET ROWCOUNT 0
SET @QUERY = "INSERT INTO tblDocTable(FileName, FileType, ImportExportID, BuildingID, Document)
SELECT '"+@fName+"' AS FileName, '"+@fType+"' AS FileType, " + cast(@fID as nvarchar(18)) + " as ImportExportID, '"+@bID+"' AS BuildingID, * FROM OPENROWSET( BULK '" +@fPath+"' ,SINGLE_BLOB)
AS Document"
EXEC (@QUERY)
This puts some values including a pdf or .doc file into a table, tblDocTable.
Is it possible to change this so that I can get the values from a table rather than as parameters. The Query would be in the form of: insert into tblDocTable (a, b, c, d) select a,b,c,d from tblimportExport.
tblImportExport has the path for the document (DocPath) so I would subsitute that field, ie. DocPath, for the @fPath variable.
Otherwise I can see only doing a Fetch next from tblIportExport where I would put every field into a variable and then run this exec query on these. Thus looping thru every row in tblImportExport.
I am deploying programatically an Excel 2007 file to a SQL Server 2005 Reporting Server. The problem is that if a file with the same name already exists, that file isn't replaced. I would like the opposite to happen. I'm using the following code:
--Executable
set svr=http://w3sdwsqld1/reportserver set src_fld="\w3sdwsqld1\deploy\SAD\ECRANS\UPDATES_20061127_190000\Ecrans\AM\Associados\" set dest_fld="Associados" set script="\w3sdwsqld1\deploy\SADECRANS\UPDATES_20061127_190000\Ecrans\AM\Associados\PublishReports.rss" REM Sample: deploy.bat http://w3sdwsqld1/reportserver "\w3sdwsqld1\deploy\SAD\ECRANS\UPDATES_20061127_190000\Ecrans\AM\Associados\" "Associados" "\w3sdwsqld1\deploy\SADECRANS\UPDATES_20061127_190000\Ecrans\AM\Associados\PublishReports.rss" for /R %src_fld% %%f in (*.xlsx) do rs -i %script% -s %svr% -v ParentFolder=%dest_fld% -v reportP="%%~nf" -v path=%src_fld% PAUSE
--rss Code
' ' Script Variables ' ' Variables that are passed on the command line with the -v switch: ' ' (a) parentFolder - corresponds to the folder that the script creates and uses ' to contain your published reports
' (b) reportP - corresponds to the report to publish
Dim ROOT As String = "/SAD/Ecrans/Ecrans/AM"
Dim definition As [Byte]() = Nothing Dim warnings As Warning() = Nothing Dim parentPath As String = ROOT + "/"+ parentFolder Dim filePath As String = path Dim report As String = reportP
'Create the parent folder Try rs.CreateFolder(parentFolder, ROOT,Nothing) Console.WriteLine("Parent folder {0} created successfully", parentFolder) Catch e As Exception
Console.WriteLine(e.Message)
End Try
'Create shared data source 'CreateSampleDataSource("Solucao_Integrada", "OLEDB-MD", "Data Source=dwareas1;Initial Catalog=SAD_Solucao_Integrada")
'Publish the sample reports PublishReport(report)
End Sub
Public Sub CreateSampleDataSource(name As String, extension As String, connectionString As String) 'Define the data source definition. Dim definition As New DataSourceDefinition() definition.CredentialRetrieval = CredentialRetrievalEnum.Integrated definition.ConnectString = connectionString definition.Enabled = True definition.EnabledSpecified = True definition.Extension = extension definition.ImpersonateUser = False definition.ImpersonateUserSpecified = True 'Use the default prompt string. definition.Prompt = Nothing definition.WindowsCredentials = False
Catch e As Exception Console.WriteLine(e.Message) End Try
End Sub
Public Sub PublishReport(ByVal reportName As String) Try Dim stream As FileStream = File.OpenRead(filePath + reportName + ".xlsx") Console.WriteLine(reportName)
definition = New [Byte](stream.Length) {} stream.Read(definition, 0, CInt(stream.Length)) stream.Close()
Catch e As IOException Console.WriteLine(e.Message) End Try
Catch e As Exception Console.WriteLine(e.Message) Console.WriteLine("Failed to publish report") End Try End Sub --------------------------------------------------------------------------------------------------------------------
Greetings, I have just arrived back into the country (NZ) and back into ASP.NET. I am having trouble with the following:An attempt to attach an auto-named database for file (file location).../Database.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share. It has only begun since i decided i wanted to use IIS, I realise VWD comes with its own localhost, but since it is only temporary, i wanted a permanent shortcut on my desktop to link to my intranet page. Anyone have any ideas why i am getting the above error? have searched many places on the internet and not getting any closer. Cheers ~ J
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
Executed as user: S233683-AD01S233683NJ3SQL05. ...at file already exists.' [SQLSTATE 42000] (Error 22048) Â ERROR -- Could not backup database: master - BACKUP DATABASE is terminating abnormally. [SQLSTATE 42000] (Error 50000) Â xp_create_subdir() returned error 183, 'Cannot create a file when that file already exists.'
I am new to msSQL and ASP, I need some help writing an SQL statement that will first check to see if a combination or record exists, if none found thant it will add it. I am working a section of a site that adds favorites to the database. Each user can have more that one favorite hence it has to check for that unique combination of the fields, UserID and FavID
My Code: Dim objConnection, objRecordset, strSQL Dim strFavID, strUserID strFavID = request.Form("favid") strUserID = request.Form("userid")
Set objConnection = Server.CreateObject("ADODB.Connection") Set objRecordset = Server.CreateObject("ADODB.Recordset") objConnection.Open Application("ConnectionString")
strSQL = "INSERT INTO FAV (UserID,FavID) (SELECT DISTINCT " & strUserID & " AS UserID " & _ strFavID & " AS FavID" & " FROM FAV)" & _ " WHERE " & strUserID & " & " & strFavID & " NOT IN (SELECT UserID, FavID FROM FAV)" response.Write(strSQL) 'response.End()
If strFavID <> "" Then On Error Resume Next objConnection.Execute(strSQL)
objConnection.Close Set objConnection = Nothing End If
This code is giving me a syntax error, how do I write the correct statement. I am using MS Access 2k
/*if key values exist don't insert new record*/ SELECT
/*if exists don't insert*/ CASE WHEN ISNULL(gradeId, -1) = -1 THEN INSERT INTO tblScores (gtStudentId, assignmentId, score) VALUES (@nStudent, @nAssignment, 0) END
FROM tblScores WHERE gtStudentId = @nStudent AND assignmentId = @nAssignment
tblScores has two fields comprising its primary key (gtStudentId, assignmentId) and the gradeId field is a required filed in this table.
I'm getting syntax errors when I click check syntax (near keywords insert from and end).
one other note: this CASE END is nested inside a BEGIN END loop, is this the problem? Is the 'End" of the 'Case' closing the 'End' of the 'Begin'?
it's me again :) I've got a - what I think - simple question. There is table A with Col1,Col2,Col3 and Table B with Col1,Col2,Col3
I want all rows from B in A. If a row already exist in A, then update all columns, else just insert the row. Can someone please help me with a small syntax. Thank you!
I am using the following code to insert records into a destination tablethat has a three column primary key i.e. (PupilID, TermID &SubjectGroup). The source table records all the pupils in a school with(amongst other things) a column (about 50) for each subject the pupilmight potentially sit. In these columns are recorded the study groupthat they belong to for those subjects. The destination table holds arecord per pupil per subject per term, against which the teacher willultimately record the pupils performance.The code as shown runs perfectly until the operator tries to insert aselection of records that include some that already exist. What I wouldlike it to do is, record those, which do not exist and discard theremainder. However, whenever a single duplicate occurs SQL rejects thewhole batch. I know that my solution will probably involve using the‘NOT EXISTS’ expression, but try as I might I cannot get it to work. Tofurther complicate things, the code is being run from within VBA usingthe RunSQL command.The variables ‘strFieldName’, ‘strGroup’ & ‘strTerm are declared at thestart of the procedure and originate from options selected on an Accessform.INSERT INTO dbo.yInterimReportData (PupilID, LastName, FirstName,TermID, SubjectGroup) SELECT PupilID, LastName, FirstName," & "'" &strTerm & "'" & "," & "'" & strGroup & "'" & "FROM dbo.Pupils WHERE (" &strFieldName & " = " & "'" & strGroup & "')Any Ideas?RegardsColin*** Sent via Developersdex http://www.developersdex.com ***
Hi I am trying to populate a table with 2 FKs as its PK (SiteID and ProductDescID). First 1) I add in all the products whose Manfacturer and Category are supposed to appear on the site and then 2) I add in all the extra products that are needed regardless of their manufacturer or category. The problem I am having is if the product has already been added to the ProductCatTable due to its Manufacturer or Cateogry but is also in the SatForceProduct table. The can’t insert duplicate PK error is thrown. I don’t know how to do this IF NOT EXISTS statement (or what ever else may be needed) so that I can check whether a line from the Forced table needs to be added. I am not passing in any parameters and I am expecting more than 1 line to be inserted in each of the statements. Please help -- 1) Populate INSERT INTO dbo.ProductCatTable (SiteID, ProductDescID) SELECT dbo.SatSite.SiteID, dbo.ProductDesc.ProductDescID FROM dbo.SatManu INNER JOIN dbo.ProductDesc ON dbo.SatManu.Manu = dbo.ProductDesc.Manu INNER JOIN dbo.SatCats ON dbo.ProductDesc.Cat = dbo.SatCats.Cat INNER JOIN dbo.SatSite ON dbo.SatManu.SatID = dbo.SatSite.SiteID AND dbo.SatCats.SatID = dbo.SatSite.SiteID 2) Add Force Ins IF NOT EXISTS(SELECT SiteID, ProductDescID FROM ProductCatTable WHERE ????????) BEGIN INSERT INTO dbo. ProductCatTable (SiteID, ProductDescID) SELECT SiteID, ProductDescID FROM dbo.SatForceProduct END Thanks in advance J
I have a 'Products' table (with: 'uid' and 'CatName' columns) and 'ProductCategory' table (with: 'uid', 'ProductID', 'CategoryID' columns).
I got stored procedure below to update or insert new row to 'ProductCategory' table whenever 'Products' table has been updated or new products has been added to it.
Update part works just fine but when new row has been added to 'Products' this storedProc dosn't insert it into 'ProductCategory' table, it does that only when 'ProductCategory' table is empty, I'm afraid it's because first column 'uid' in 'ProductCategory' table is an Identity column... I’m not sure how should I go about that problem. This is my stored procedure:
DECLARE @CatNo INT, @CatName varchar(10) SET @CatNo = 2 SET @CatName = 'bracket'
IF exists (SELECT ProductID from ProductCategory, Products where ProductCategory.ProductID = Products.uid and Products.CatName = @CatName ) BEGIN UPDATE ProductCategory SET CategoryID = @CatNo FROM Products WHERE Products.CatName = @CatName and ProductCategory.ProductID = Products.uid END ELSE BEGIN INSERT INTO ProductCategory ( ProductID, CategoryID) SELECT uid, @CatNo FROM Products WHERE Products.CatName = @CatName END
SET @CatNo = 3 SET @CatName = 'cable'
IF exists (SELECT ProductID from ProductCategory, Products where ProductCategory.ProductID = Products.uid and Products.CatName = @CatName ) BEGIN UPDATE ProductCategory SET CategoryID = @CatNo FROM Products WHERE Products.CatName = @CatName and ProductCategory.ProductID = Products.uid END ELSE BEGIN INSERT INTO ProductCategory ( ProductID, CategoryID) SELECT uid, @CatNo FROM Products WHERE Products.CatName = @CatName END (... Goes for another 37 categories)
I'm using MSSQL and PHP. I've got the following sql statement:
$msquery = IF NOT EXISTS (SELECT SerienNr FROM tbl_Auftrag a WHERE a.SerienNr='PC8') INSERT INTO tbl_Auftrag (BMS_AuftragsNr, SerienNr, AuftraggNr, Zieltermin, Kd_Name) VALUES ('455476567','PC8','1','2006-3-2','Fritz')
The Statement itself works fine, but i've got a problem getting a return value whether the insert has succeed, or not. :confused: mssql_query() always returns true if there occured no error in the statement. But i need to know if the insert procedded or not. I tried:
In MS Access I can do in one SQL statement a update if exists else ainsert.Assuming my source staging table is called - SOURCE and my targettable is called - DEST and both of them have the same structure asfollowsKeycolumns==========MaterialCustomerYearNonKeyColumns=============SalesIn Access I can do a update if the record exists else do a insert inone update SQL statement as follows:UPDATE DEST SET DEST.SALES = SOURCE.SALESfrom DEST RIGHT OUTER JOIN SOURCEON (DEST.MATERIAL = SOURCE.MATERIAL ANDDEST.CUSTOMER = SOURCE.CUSTOMER ANDDEST.YEAR = SOURCE.YEAR)This query will add a record in SOURCE into DEST if that record doesnot exist in DEST else it does a update. This query however does notwork on SQL 2000Am I missing something please share your views how I can do this inSQL 2000.ThanksKaren
I had implemented as in the link to insert or update http://blogs.conchango.com/jamiethomson/archive/2006/09/12/SSIS_3A00_-Checking-if-a-row-exists-and-if-it-does_2C00_-has-it-changed.aspx
What i want to know is... how can i assume there are no duplicate records. I used Distinct keyword and queried it showed me all are distint but some where i find some duplicates just don't know why i am having when i look at the data both are exactly same...
I am checking to see if the source record is available in the target table using a lookup transformation and if not found i have to insert this record. I have connected the error flow of the lookup transformation to the target. I am acheiving expected results, but is this the best practise? I have not connected to the green arrow to any task.
I am very new to db. so pardon me for some stupid questions.
I have 3 tables Table1, Table2, and table3. Table1 and table2 has 5 columns each and table3 has 4 columns. i have 6 or 7 csv files (these number of files can change) uploaded to a upload directory. these csv filename contains name of the table. for example table1_ab.csv, table1_cd.csv, table2_ef.csv, table2_gh.csv, table3.aa.csv, table3_bb.csv.
a person goes to a web page and clicks a button. This is what the button should do. 1) Check how many files are there in the upload directory. 2) use bulk insert to individually insert each csv file into their respective table (the name of the table is in file name). 3) Copy the csv file into backup directory and delete the file from upload directory.
I am using vb.net. any help would me much appriciated.