Creating transient table with copy grants as option - snowflake-cloud-data-platform

The requirement is to create table in Snowflake by using an Airflow JOB.
create or replace transient table humanities_timesheet copy grants as
(
worker_name varchar(300),
employee_id varchar(20)
)
Syntax error: unexpected 'worker_name'.
syntax error line 3 at position 25 unexpected ','. (line 12)
without the copy grants as the code works and table gets created under the right schema.
When I used CTE was able to create transient tables with the copy grants as option
create
or replace transient table dq_mart.working.reconciliation_workday_worker_position copy grants as
with workday_worker_position as (
select * from humanities
)
Any suggestions on using copy grants as when creating a new transient table would be highly appreciated.

Just a problem of order into your syntax.
This works :
CREATE OR REPLACE TRANSIENT TABLE humanities_timesheet (
worker_name varchar(300),
employee_id varchar(20)
) COPY GRANTS
;
Documentation here : CREATE TABLE

Related

Creating temp tables in sybase

I am running into an issue with creating temp tables in Sybase db. We have a sql where we create a temp table, insert/update it and do a select * from it at the end of get some results. We are invoking this sql from the service layer using spring jdbc tmplate. The first run works fine, but the next subsequesnt runs fails with error
cannot create temporary table <name>. Prefix name is already in use by another temorary table
This is how I am checking if table exists:
if object_id('#temp_table') is not null
drop table #temp_table
create table #temp_table(
...
)
Anything I am missing here?
Might not be a great response, but I also have that problem and I have 2 ways around it.
1. Do the IF OBJECT_ID Drop Table as a separate execute prior to the query
2. Do the Drop Table without the IF OBJECT_ID() right after your query.
You are really close but temp tables require using the db name before too.
IF OBJECT_ID('tempdb..#Results') IS NOT NULL
DROP TABLE #Results
GO
It would be the same if you were checking if a user table in another database existed.
IF OBJECT_ID('myDatabase..myTable') IS NOT NULL
DROP TABLE myDatabase..myTable
GO
NOTE: A bit more info on BigDaddyO's first suggestion ...
The code snippet you've provided, when submitted as a SQL batch, is parsed as a single unit of work prior to the execution. Net result is that if #temp_table already exists when the batch is submitted, then the compilation of the create table command will generate the error. This behavior can be seen in the following example:
create table #mytab (a int, b varchar(30), c datetime)
go
-- your code snippet; during compilation the 'create table' generates the error
-- because ... at the time of compilation #mytab already exists:
if object_id('#mytab') is not NULL
drop table #mytab
create table #mytab (a int, b varchar(30), c datetime)
go
Msg 12822, Level 16, State 1:
Server 'ASE200', Line 3:
Cannot create temporary table '#mytab'. Prefix name '#mytab' is already in use by another temporary table '#mytab'.
-- same issue occurs if we pull the 'create table' into its own batch:
create table #mytab (a int, b varchar(30), c datetime)
go
Msg 12822, Level 16, State 1:
Server 'ASE200', Line 1:
Cannot create temporary table '#mytab'. Prefix name '#mytab' is already in use by another temporary table '#mytab'.
As BigDaddyO has suggested, one way to get around this is to break your code snippet into two separate batches, eg:
-- test/drop the table in one batch:
if object_id('#mytab') is not NULL
drop table #mytab
go
-- create the table in a new batch; during compilation we don't get an error
-- because #mytab does not exist at this point:
create table #mytab (a int, b varchar(30), c datetime)
go

Is There A Database Engine that Allows for Queriable Field Constraint Specified by RegEx?

I'm looking for a database engine that can handle data constraints specified via RegEx. So in addition to the datatype, I want to be able to control the format of the data. E.g. a varchar(255) field could be further restrained to be like [a-zA-Z0-9 ].
I need the RegEx to be able to be queried too, so I can share those constraints throughout the n-tier system to enforce on several levels. E.g. MySQL allows for querying of information_schema to get meta data, and other database engines have similar ways.
I did a post yesterday (MySQL Queriable Field Constraint by RegEx), referencing things I read, but doesn't look promising with MySQL, so I'm opening this up to any db engine, although I would prefer MS SQL, Oracle, DB2 or MySQL, as it'll be easier to sell the business on.
Is there a database engine out there that allows for these regex restrictions? If so, which one is it and how do the constraints get set and queried?
In Oracle you can specify custom constraints, in which you can use functions that evaluate regexp; for example:
SQL> create table test_pattern ( txt varchar2(1000))
2 /
Table created.
SQL> alter table test_pattern add constraint check_pattern check (regexp_instr(txt, '^START') != 0)
2 /
Table altered.
SQL> insert into test_pattern values ('START a d f g ')
2 /
1 row created.
SQL> insert into test_pattern values ('_START a d f g ')
2 /
insert into test_pattern values ('_START a d f g ')
*
ERROR at line 1:
ORA-02290: check constraint (SIUINTEGRA.CHECK_PATTERN) violated
You can get informations on constraints you set with something like:
select *
from dba_constraints
where table_name = 'TEST_PATTERN'
Here is a wildcard example in sql server for this.
create table #Something
(
SomeValue varchar(255)
, constraint MyCheck CHECK (SomeValue like '[a-z][a-z][0-9]%')
)
insert #Something
select 'ab3adoofnod'
--(1 row(s) affected)
insert #Something
select 'a3b3adoofnod'
Msg 547, Level 16, State 0, Line 1
The INSERT statement conflicted with the CHECK constraint "MyCheck". The conflict occurred in database "tempdb", table "dbo.#Something__________________________________________________________________________________________________________0000000000DD", column 'SomeValue'.
The statement has been terminated.
If you want to use some t-sql to view the definitions of your check constraints you can use the sys.check_constraints catalog view.
Here is an example to view ALL the check constraints for the table above. The definition columns will provide the wildcard searching as defined in the constraint.
select *
from tempdb.sys.check_constraints
where parent_object_id = object_id('tempdb..#Something')

Insert data from 1 table to another table in my local sql

Hi I need to run this script to insert data from another server to my local sql server. How I can identify the path?
CMMS is the name of the table that is in my local sql. My pc name is itfg234. what should I replace for CMMS in this query.
SELECT * INTO CMMS
FROM (
SELECT N'178670' AS [_IdxIdentity], N'E94E6A98-B71A-41ED-8B4B-F6472BA72ECD' AS [Contract_Other_DateBooked] ) t;
GO
CREATE TABLE customer(
customer_id VARCHAR(10) NOT NULL PRIMARY KEY,
customer_name VARCHAR(20) NOT NULL,
address VARCHAR(40) NOT NULL
);
CREATE TABLE employee(
emp_id VARCHAR(10) NOT NULL PRIMARY KEY,
emp_name VARCHAR(30) NOT NULL,
contact_no VARCHAR(10) NOT NULL
);
I need insert data from customer to employees
INSERT customer SELECT customer_id, customer_name, address FROM employee;
If the destination table already exists then you can't use SELECT * INTO or you'll get error
There is already an object named 'CMMS' in the database.
SELECT INTO creates the destination table. Use INSERT INTO dbo.CMMS ([column names]) instead.
The query is cut off so I can't see the entire subquery but I'll just mention you should give it an alias or you may get
Incorrect syntax near ')'.
If you are planning to run the command on the source server I recommend that you design it to run on the destination server and select from source using a linked server or OPENROWSET function. It's easier to pull data than push it.
Hope this helps.
try this
CREATE TABLE new_table_name LIKE old_table_name;
INSERT new_table_name SELECT * FROM old_table_name;
hope this one help you.

SQL Server Copy a table from one database to another and retain identity field

I am copying a table from one database to another, actually from one connection to another. The problem is that the key field is an identity field. In the new database in does not the identity property.
So when I try to insert into the new table I get an error because the field which used to have an identity property cannot be null. I could create a new identity field and then rename it to the original name but then the values would be out of sync with the other tables it is link to.
Thanks in advance for any help.
Bob
The answer can be found in the second comment. I'll paste it here:
CREATE TABLE dbo.Tmp_Names
(
Id int NOT NULL
IDENTITY(1, 1),
Name varchar(50) NULL
)
ON [PRIMARY]
go
SET IDENTITY_INSERT dbo.Tmp_Names ON
go
IF EXISTS ( SELECT *
FROM dbo.Names )
INSERT INTO dbo.Tmp_Names ( Id, Name )
SELECT Id,
Name
FROM dbo.Names TABLOCKX
go
SET IDENTITY_INSERT dbo.Tmp_Names OFF
go
This will create table [db2].[dbo].[YoutableNameYouWantInDb2] in db2 with same structure as in db1 and copy all data from [db1].[dbo].[yourTableName].
SELECT * INTO [db2].[dbo].[YoutableNameYouWantInDb2]
FROM [db1].[dbo].[yourTableName]

What is the preferred method of creating, using and dropping temp tables in sql server?

When using temp tables in SQL Server stored procs, is the preferred practice to;
1) Create the temp table, populate it, use it then drop it
CREATE TABLE #MyTable ( ... )
-- Do stuff
DROP TABLE #MyTable
2) Check if it exists, drop it if it does, then create and use it
IF object_id('tempdb..#MyTable') IS NOT NULL
DROP TABLE #MyTable
CREATE TABLE #MyTable ( ... )
3) Create it and let SQL Server clean it up when it goes out of scope
CREATE TABLE #MyTable ( ... )
-- Do Stuff
I read in this answer and its associated comments, that this can be useful in situations where the temp table is reused that SQL Server will truncate the table but keep the structure to save time.
My stored proc is likely to be called pretty frequently, but it only contains a few columns, so I don't know how advantageous this really is in my situation.
You could test and see if one method outperforms another in your scenario. I've heard about this reuse benefit but I haven't performed any extensive tests myself. (My gut instinct is to explicitly drop any #temp objects I've created.)
In a single stored procedure you should never have to check if the table exists - unless it is also possible that the procedure is being called from another procedure that might have created a table with the same name. This is why it is good practice to name #temp tables meaningfully instead of using #t, #x, #y etc.
I follow this approach:
IF object_id('tempdb..#MyTable') IS NOT NULL
DROP TABLE #MyTable
CREATE TABLE #MyTable ( ... )
// Do Stuff
IF object_id('tempdb..#MyTable') IS NOT NULL
DROP TABLE #MyTable
Reason: In case if some error occurs in sproc, and created temp table is not dropped and when the same sproc is called with check for existence, it will raise error that table cannot be created, and will never get successfully executed unless the table is dropped. So always perform check for the existence of and object before creating it.
When using temp tables my preferred practice is actually a combination of 1 and 2.
IF object_id('tempdb..#MyTable') IS NOT NULL
DROP TABLE #MyTable
CREATE TABLE #MyTable ( ... )
// Do Stuff
IF object_id('tempdb..#MyTable') IS NOT NULL
DROP TABLE #MyTable

Resources