Hello everyone!
I am facing a problem here that may be easy to solve. I have a query to add lines to a table. This query is executed every 3 hours, but when it is going to be executed, i want to know if that ID already have these records, if it doesn`t, add, if it does, skip.
How can I do it?
this is the ddl
use [mydb] IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'table_info') AND type in (N'U')) BEGIN CREATE TABLE dbo.table_info ( id [int] IDENTITY NOT NULL, project_id INTEGER NOT NULL, document_type NVARCHAR(100) NOT NULL, document_location NVARCHAR(100), PRIMARY KEY (ID) ) END
to add the data, I did this:
DECLARE @1 VARCHAR(100) = 'Info 1' DECLARE @2 VARCHAR(100) = 'Info 2' DECLARE @3 VARCHAR(100) = 'Info 3' DECLARE @4 VARCHAR(100) = 'Info 4' DECLARE @5 VARCHAR(100) = 'Info 5' DECLARE @TempTab TABLE (id INT IDENTITY, project INT) INSERT INTO @TempTab (project) SELECT id FROM mydb.dbo.project_id DECLARE @QtTab INT, @CurCode INT = 1, @TabName VARCHAR(100) = 'mydb.dbo.table_info' SELECT @QtTab = COUNT(*) FROM @TempTab While @CurCode <= @QtTab Begin DECLARE @Proj int = (SELECT project FROM @TempTab WHERE id = @CurCode) EXEC ('INSERT INTO ' + @TabName + ' (project_id, document_type, document_location) values (' + @Proj + ', ' + '''' + @1 + '''' + ', ' + '''' + @1 + '''' + ' ), (' + @Proj + ', ' + '''' + @2 + '''' + ', ' + '''' + @2 + '''' + ' ), (' + @Proj + ', ' + '''' + @3 + '''' + ', ' + '''' + @3 + '''' + ' ), (' + @Proj + ', ' + '''' + @4 + '''' + ', ' + '''' + @4 + '''' + ' ), (' + @Proj + ', ' + '''' + @5 + '''' + ', ' + '''' + @5 + '''' + ' ) ) Set @CurCode += 1 End
If I run this, every project will receive all the time the new lines, I need it to add only if these doesn`t exist.
How can I do this?