Insert oracle data based on column position - database

Im trying to insert oracle data based on a specific order of my columns. This is what i have tried but i get a sql statement not properly ended error.
INSERT INTO owner.users u
(
select column_name
from all_tab_cols
where owner ='owner' AND table_name= 'users' AND virtual_column='NO'
order by 1
)
VALUES ('foo','bar')

Related

SQL Server stored procedure error handling with if exists

I have five databases, In that three databases having column Countries and two databases having column Countryrelease..
I am using a cursor, so if I use exists that particular column is throwing an error that column not exists how to handle this one.
Syntax
if exists(select 1 from table where column name='Countries')
select do some operation
else
select do some operation
You want to make use of the meta data within the SQL instance.
This will work for you ...
if (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'YourTableName' AND COLUMN_NAME = 'Countries') = 1
-- The "Countries" column exists
select do some operation
else
select do some operation

how to track a deletion in the future?

I have a table in my Datamart; users are supposed to only read from that table… I checked and the count of the table went down, meaning, someone, a SP or a job, deleted records, and I sense it is not the first time.
My question: what is the less invasive, and simpler way of tracking this: I do not want to prevent this; I want to get the person’s name, or the SP/Job name, and the exact time it happened.
I am using: Microsoft SQL Server 2012 (SP1) - 11.0.3000.0 (X64): Business Intelligence Edition (64-bit) on Windows NT 6.2 (Build 9200: ) (Hypervisor)
I have ‘simple’ recovery model, I assume tracking it in the past is really challenging, so I am happy with retrieving this information in the future.
You can use a AFTER DELETE trigger on your table and log deleted values into a history log table with user information and deletion time, etc as follows
CREATE TRIGGER dbo.myTableDeleteTrigger
ON dbo.myTable
AFTER DELETE
AS
INSERT INTO myTableHistory (
-- columns from myTable
DeletedDate,
DeletedByUserId
)
SELECT
-- delete column values from Deleted temp table
GETDATE(),
USER_ID()
FROM Deleted
GO
I used a similar trigger to log data changes for insert, update and delete DMLs on a SQL database table as I explained in the referred tutorial
This below code will generate the Triggers for every table in your database.
Note: You can exclude the tables which you don't want the track in CTE
;WITH CTE AS(
SELECT TAB.name FROM SYS.objects TAB
where TAB.type='U'
)
SELECT '
GO
CREATE TRIGGER [dbo].[TRG_'+NAME+'_LOG] ON [dbo].['+NAME+']
FOR UPDATE,DELETE
AS
INSERT INTO LOG_'+NAME+'
(LOG_DTE,'+(SELECT STUFF((
SELECT ', '+ COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME=NAME FOR XML PATH('')),1,1,''))+')
SELECT getdate(),'+(SELECT STUFF((
SELECT ', '+ COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME=NAME FOR XML PATH('')),1,1,''))+'
from deleted
PRINT ''AFTER TRIGGER FIRED''
' FROM CTE order by name OFFSET 81 ROWS FETCH NEXT 571 ROWS ONLY
But before you need to create a table for every table with the name prefix Log_ of actual table.
Ex: If you have table Employee (Eid int, EName Varchar(250))
You need to have a table like
Log_Employee (LOG_EID int identity,Log_DTe Datetime, EID int FK, EName Varchar(250))

How to frame insert statements from select statement data in SQL Server?

I've selected some data from a table it gives some rows in as result. Now, I want to generate insert statements from result data in SQL Server.
Please suggest me any solutions.
If the destination table is a new table,
you may use SQL SELECT INTO Statement.
We can copy all columns into the new table:
SELECT *
INTO newtable [IN externaldb]
FROM table1;
Or we can copy only the columns we want into the new table:
SELECT column_name(s)
INTO newtable [IN externaldb]
FROM table1;
The new table will be created with the column-names and types as defined in the SELECT statement. You can apply new names using the AS clause.
Like this,
SELECT 'insert into tabledestination (col1destination,col2destination)
values (' + col1source + ',' + col2source + ')'
FROM tablesource;

Error inserting comma separated values in Table: SQL Server 2008

I have two tables called 'ticket' and 'ticket_category'.
'Ticket' table has a column 'Ticket_Uid' and its type is 'UniqueIdentifier'.
Each 'ticket_uid' in 'ticket' table has one-to-many mappings in 'ticket_category' table.
E.g.
'Ticket' table:
Ticket_Uid
100
Ticket_Category:
Ticket_Uid Ticket_Category_Uid
100 ABC
100 DEF
100 XYZ
I want to create the following table named 'comment_mining':
Ticket_Uid Category_List
100 ABC,DEF,XYZ
The table has already been created using the following:
create table dbo.comment_mining
(
Ticket_UID [uniqueidentifier] NOT NULL,
time_created datetime,
time_closed datetime,
total_time_taken int,
category_list nvarchar(500),
comment_list varchar(8000)
);
I have already created this table and populated the 'Ticket_Uid' column.
For inserting into the 'category_list' column, I am using the following query:
insert into dbo.comment_mining(category_list)
SELECT
(SELECT distinct convert(varchar(500),category_id) + ',' AS [text()]
FROM ticket_category pr
WHERE pr.ticket_uid = p.ticket_uid
FOR XML PATH (''))
AS Category_list
FROM comment_mining p
When I run the above query, it gives me the following error:
Msg 515, Level 16, State 2, Line 1
Cannot insert the value NULL into column 'Ticket_UID', table 'Support_Saas.dbo.comment_mining'; column does not allow nulls. INSERT fails.
The statement has been terminated.
(which is strange as I am not even inserting in the 'Ticket_Uid' column)
When I run the same query without the insert statement, it executes perfectly. The query is as follows:
SELECT
(SELECT distinct convert(varchar(500),category_id) + ',' AS [text()]
FROM ticket_category pr
WHERE pr.ticket_uid = p.ticket_uid
FOR XML PATH (''))
AS Category_list
FROM comment_mining p
Yes there are some NULL values when the above query is run, but 'category_list' column in 'comment_mining' table can take NULL values. Why is the error on 'ticket_Uid' column?
Would someone please be able to explain why this is happening and what's the cure to this?
P.S. - I am new to SQL.
The reason you have the insert error on table comment_mining is because you set the Ticket_Uid column as not null; however, since it does not have a default value, the insert fails because whether you're inserting that field specifically or not, when a row is created, all columns must be filled in or be null.
You can do one of 2 things:
Change the structure of the comment_mining table to have a default value for Ticket_Uid (You can do this in the table designer or with code:
Example 1:
Alter Table comment_mining
Add Constraint DF_CommentMining_1 default NewID() for Ticket_UID
Make your insert explicitly include a generated uniqueidentifier (GUID) value by using the SQL NewID() function to populate the Ticket_UID UniqueIdentifier column
Example 2:
insert into dbo.comment_mining(Ticket_Uid, category_list)
SELECT NewID(),
[ your subquery ]...
In both cases, you're now satisfying the NOT NULL constraint on comment_mining.Ticket_UID, either by making it automatically populate itself, or by supplying a value.
try this,
;with cte as
(
select 100 Ticket_Uid,'ABC' Ticket_Category_Uid union all
select 100 , 'DEF' union all
select 100, 'XYZ'
)
select distinct b.Ticket_Uid,
stuff((select ','+a.Ticket_Category_Uid from cte a where a.Ticket_Uid=b.Ticket_Uid for xml path('')),1,1,'')
from cte b

Merge query in SQL Server 2008

I having the scenario of loading the data from source table to target table. If the data from source is not present in target, then i need to insert. If it is present in the target table already, then update the status of the row to 'expire' and insert the column as new row. I used Merge query to do this. I can do insert if not exists and i can do update also. But while trying to insert when matched, it says insert not allowed in 'when matched' clause.
Please help me.. Thanks in advance
If you want to perform multiple actions for a single row of source data, you need to duplicate that row somehow.
Something like the following (making up table names, etc):
;WITH Source as (
SELECT Col1,Col2,Col3,t.Dupl
FROM SourceTable,(select 0 union all select 1) t(Dupl)
)
MERGE INTO Target t
USING Source s ON t.Col1 = s.Col1 and s.Dupl=0 /* Key columns here */
WHEN MATCHED THEN UPDATE SET Expired = 1
WHEN NOT MATCHED AND s.Dupl=1 THEN INSERT (Col1,Col2,Col3) VALUES (s.Col1,s.Col2,s.Col3);
You always want the s.Dupl condition in the not matched branch, because otherwise source rows which don't match any target rows would be inserted twice.
From the example you posted as a comment, I'd change:
MERGE target AS tar USING source AS src ON src.id = tar.id
WHEN MATCHED THEN UPDATE SET D_VALID_TO=#nowdate-1, C_IS_ACTIVE='N', D_LAST_UPDATED_DATE=#nowdate
WHEN NOT MATCHED THEN INSERT (col1,col2,col3) VALUES (tar.col1,tar.col2,tar.col3);
into:
;WITH SourceDupl AS (
SELECT id,col1,col2,col3,t.Dupl
FROM source,(select 0 union all select 1) t(Dupl)
)
MERGE target AS tar USING SourceDupl as src on src.id = tar.id AND Dupl=0
WHEN MATCHED THEN UPDATE SET D_VALID_TO=#nowdate-1, C_IS_ACTIVE='N', D_LAST_UPDATED_DATE=#nowdate
WHEN NOT MATCHED AND Dupl=1 THEN INSERT (col1,col2,col3) VALUES (src.col1,src.col2,src.col3);
I've changed the values in the VALUES clause, since in a NOT MATCHED branch, the tar table doesn't have a row to select values from.
Check out one of those many links:
Using SQL Server 2008's MERGE Statement
MERGE on Technet
Introduction to MERGE statement
SQL Server 2008 MERGE
Without actually knowing what your database tables look like, we cannot be of more help - you need to read those articles and figure out yourself how to apply this to your concrete situation.

Resources