INSERT where not exists in SingleStore - database

I am trying to perform INSERT WHERE NOT EXISTS in singlestore using spring jpa native quey but I'm getting Sql grammar exception.
I'm using sql5dialect.
Can someone help me with performing the query
Query - INSERT INTO table(col1) VALUES ('colValue') WHERE NOT EXISTS (SELECT 1 from table WHERE col2 = 'coValue'
I have also tried
INSERT INTO table(col1) Select ('colValue') from dual WHERE NOT EXISTS (SELECT 1 from table WHERE col2 = 'coValue'

Related

Can we use Parameterized Views in Snowflake?

Can we use Parameterized Views in Snowflake. Such as pass the table name or database name as parameters instead of hardcoding it?
I think your best bet is to use session variables in conjunction with a regular view.
A session variable can be referenced in the view DDL, and will need to be set in any sessions querying the view.
To do this, you can make use of the IDENTIFIER function in Snowflake, which lets you use text as an object identifier.
create table t1 (col1 number, col2 number);
create table t2 (col1 number, col2 number);
set ti = 't1';
create view v1 as select col1, col2 from identifier($ti);
Before you query the view, you will need to set the session variable (ti in this case) to the table name (fully qualified if need be).
set ti = 't1';
select * from v1; -- returns data from t1
set ti = 't2';
select * from v1; -- returns data from t2
I have not found a way to do this, so I've created what I call a "wrapper view" in the past when I need something like this, example as follows.
I hope this helps...Rich
--create source tables and test records
CREATE TABLE t1 (id NUMBER, str VARCHAR);
CREATE TABLE t2 (id NUMBER, str VARCHAR);
CREATE TABLE t3 (id NUMBER, str VARCHAR);
INSERT INTO t1 VALUES(1, 'record from t1');
INSERT INTO t1 VALUES(2, 'record from t1');
INSERT INTO t2 VALUES(100, 'record from t2');
INSERT INTO t2 VALUES(101, 'record from t2');
INSERT INTO t3 VALUES(998, 'record from t3');
INSERT INTO t3 VALUES(999, 'record from t3');
--create the "wrapper" view
CREATE VIEW vw_t AS (
SELECT 't1' as table_name, * FROM t1
UNION ALL
SELECT 't2' as table_name, * FROM t2
UNION ALL
SELECT 't3' as table_name, * FROM t3);
--try it out
SELECT *
FROM vw_t
WHERE table_name = 't3';
--results
TABLE_NAME ID STR
t3 998 record from t3
t3 999 record from t3
I think the best way to handle something like this would be to create a UDTF that acts like a view that has been parameterized. So, in essence, you'd reference the UDTF like a view and pass the parameters into the UDTF, which would then return the data that you wish to use. Note that Snowflake has 2 options for UDTF (SQL and Javascript):
https://docs.snowflake.net/manuals/sql-reference/udf-table-functions.html
https://docs.snowflake.net/manuals/sql-reference/udf-js-table-functions.html
Although when using the interactive SQL worksheet on Snowflake, you can do this:
SET target_table_name='myTable';
SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME=$target_table_name
That does not work programmatically. Instead, as described here, a parameterized query such as a view uses this syntax:
SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME=(?)
And yes, the name of that first (?) parameter is 1.
I'm working on my SnowflakeSQLHelper (an adaptation of the Microsoft Patterns and Practices) that will help when attaching parameters.

Export data from Microsoft SQL Server using a query to target data

I know how to generate scripts to script insert lines allowing me to backup some data. I was wondering though if it was possible to write a query (using WHERE clause as an example) to target a very small subset of data in a very large table?
In the end I want to generate a script that has a bunch of insert lines and will allow for inserting primary key values (where it normally would not let you).
SSMS will not let you to have the INSERT queries for specific rows in a table. You can do this by using GenerateInsert stored procedure. For example :
EXECUTE dbo.GenerateInsert #ObjectName = N'YourTableName'
,#SearchCondition='[ColumnName]=ColumnValue';
will give you similar result for the filtered rows specified in the #SearchCondition
Let's say your table name is Table1 which has columns Salary & Name and you want the insert queries for those who have salary greater than 1000 whose name starts with Mr., then you can use this :
EXECUTE dbo.GenerateInsert #ObjectName = N'Table1'
,#SearchCondition='[Salary]>1000 AND [Name] LIKE ''Mr.%'''
,#PopulateIdentityColumn=1;
If I read your requirement correctly, what you actually want to do is simply make a copy of some data in your table. I typically do this by using a SELECT INTO. This will also generate the target table for you.
CREATE TABLE myTable (Column1 int, column2 NVARCHAR(50))
;
INSERT INTO myTable VALUES (1, 'abc'), (2, 'bcd'), (3, 'cde'), (4, 'def')
;
SELECT * FROM myTable
;
SELECT
*
INTO myTable2
FROM myTable WHERE Column1 > 2
;
SELECT * FROM myTable;
SELECT * FROM myTable2;
DROP TABLE myTable;
DROP TABLE myTable2;
myTable will contain the following:
Column1 column2
1 abc
2 bcd
3 cde
4 def
myTable2 will only have the last 2 rows:
Column1 column2
3 cde
4 def
Edit: Just saw the bit about the Primary Key values. Does this mean you want to insert the data into an existing table, rather than just creating a backup set? If so, you can issue SET IDENTITY_INSERT myTable2 ON to allow for this.
However, be aware that might cause issues in case the id values you are trying to insert already exist.

Select Statement Nested Query

I am using Zapier to add rows to SQL Server tables. However, I have needed to use the find row via custom query and create specific INSERT statements
However, Zapier will only work if there is select statement at the start of the query. The insert works but the flow fails as Zapier can only process one query / statement.
My query is
insert into Table_A (EntryID, FirstName)
output inserted.EntryID, inserted.FirstName into Table_B (EntryID, Firstname)
values (102, 'Fred')
select *
from ILR_Test
where EntryID = 102
Is there a way of making the insert activity part of a select statement through a subquery or some other way.
Thanks

How to compare varbinary data type in where clause

I have a linked server that is created to pull user details from a specific Organisation Unit with a scheduled sql job agent.
The table is created to hold user details has a column for ObjectGUID number and the type is defined as varbinary(50) (I am not sure why..).
The process checks if there is a new user by comparing the ObjectGUID number the saved Users table and if there is a new number then insert the new user in the table.
However I have noticed that the comparisons actually not really working properly.
SELECT
tbl.objectGUID AS UserGUID
FROM [dbo].[ActiveDirectoryUsers] tbl
WHERE tbl.objectGUID NOT IN (SELECT UserGUID FROM dbo.Users)
When I create a new user the new user is appearing in the ActiveDirectoryUsers view.
but when the where clause added to compare results with Users table then result is always empty. It looks like I need to cast or convert the varbinary to varchar then do the comparisons. I tried to cast the varbinary into varchar and uniqueidentifier but still it does not work.
Any idea how would I do the comparisons?
Update
CREATE VIEW [dbo].[ActiveDirectoryUsers] AS
SELECT "SAMAccountName" AS sAMAccountName, "mail" AS Email,
"objectGUID" AS objectGUID
FROM OpenQuery(ADSI, 'SELECT SAMAccountName, mail, objectGUID
FROM ''ldapconnectionstring.com''')
An example of objectGUID in the Users table
0x1DBCC071C69C8242B4895D42750969B1
You should not cast varbinary to smth particular to be able to use it in WHERE clause.
Your problem is that you use NOT IN where NULL values are present.
Try to execute my code first as it is (it will return 1 row) and then uncomment NULL value insert and execute it again.
This time you'll get 0 rows:
declare #t1 table (guid varbinary(50))
insert into #t1
values(0x1DBCC071C69C8242B4895D42750969B1)--, (null);
declare #t2 table (guid varbinary(50))
insert into #t2
values(0x1DBCC071C69C8242B4895D42750969B1), (0x1DBCC071C69C8242B4895D42750969B2);
select *
from #t2 t2
where t2.guid not in (select guid from #t1);
To fix your problem, try to use NOT EXISTS instead of NOT IN like this:
select *
from #t2 t2
where not exists (select *
from #t1 t1
where t1.guid = t2.guid);
In your case the code should be like this:
SELECT tbl.objectGUID AS UserGUID
FROM [dbo].[ActiveDirectoryUsers] tbl
WHERE not exists (SELECT *
FROM dbo.Users u
where u.UserGUID = tbl.objectGUID );

Getting an Error on inserting data when using Linked Server Queries

UPDATE : The issue was col1 was hiereachyid type and even a select didnt work for it.
Hi all,
I am getting this error -
Objects exposing columns with CLR types are not allowed in distributed queries. Please use a pass-through query to access remote object '"RemoteDb"."dbo"."RemoteTable"'.
I have already setup the linked server [RemoteServer.dev.com].I was trying to perform an bulk insert from a remote table into the current table something like this -
INSERT INTO [CurrentDb].[dbo].[Mytable]
(
col1,
col2
)
SELECT
col1,col2
FROM [RemoteServer.dev.com].[RemoteDb].[dbo].[RemoteTable]
Can anyone please help me out..thanks.
As the error indicates, you need a pass-through query here because of the datatypes. Try this:
INSERT INTO [CurrentDb].[dbo].[Mytable]
(
col1,
col2
)
SELECT col1, col2
FROM OPENQUERY([RemoteServer.dev.com], 'SELECT col1, col2 FROM [RemoteDb].[dbo].[RemoteTable]')

Resources