Check if a table exists in Kusto language? - azure-log-analytics

Is there a way to programmatically check if a table is existent in log analytics using the kusto language?
For example, let's suppose I want to check if a workspace contains the VMConnection table something like :
IF OBJECT_ID('*objectName*', 'U') IS NOT NULL
OR
IF (EXISTS (SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'TheSchema'
AND TABLE_NAME = 'TheTable'))
BEGIN
--Do Stuff
END

Perhaps, you can use next technique to check if there is non-empty table present:
let hasNonEmptyTable = (T:string)
{
toscalar( union isfuzzy=true ( table(T) | count as Count ), (print Count=0) | summarize sum(Count) ) > 0
};
let TableName = 'StormEvents';
print Table=TableName, IsPresent=iif(hasNonEmptyTable(TableName), "Table present", "Table not preset")
You can try running it online using https://dataexplorer.azure.com/clusters/help/

Related

How to write a query which selects from a table that is returned by another query

I have table which has basically 2 rows containing the name of failure and the main table i want to write a query such that
Select main
from xyz
will return the table name like abc.
Now I want to get the data from the abc table
Select *
from
(select main
from xyz)
which returns abc.
How can I write it ?
You must use dynamic sql.
Note, that you can't use "SELECT to nowhere" in a compound statement in Db2. That is, the following code is erroneous.
BEGIN
SELECT * FROM MYTAB;
END#
This is why you need to store the result of SELECT somewhere. You may use Global Temporary Tables for that presuming, that USER TEMPORARY TABLESPASE is available to use for your user.
--#SET TERMINATOR #
BEGIN
DECLARE V_STMT VARCHAR (500);
SELECT
'DECLARE GLOBAL TEMPORARY TABLE SESSION.RESULT'
|| ' AS (SELECT * FROM '
|| MAIN
|| ') WITH DATA WITH REPLACE '
|| 'ON COMMIT PRESERVE ROWS NOT LOOGED'
INTO V_STMT
FROM XYZ
-- place your WHERE clause here if needed
FETCH FIRST 1 ROW ONLY
;
EXECUTE IMMEDIATE V_STMT;
END
#
SELECT * FROM SESSION.RESULT
#
dbfiddle link.
Here is a solution on stack that shows how to get the table names from your database
DB2 Query to retrieve all table names for a given schema
Then you could take your failure table and join into it based off of the table name, that should match your errors to the table that match on the table name. I'm not a 100% sure of your question but I think this is what you are asking.
The inner system query has schema and name. Type is T for table. See IBM link below for column reference. You could run the query wide open in the inner query to look for the tables you want. I would recommend using schema to isolate your search.
https://www.ibm.com/docs/en/db2-for-zos/11?topic=tables-systables
SELECT
ft.*
, st.*
FROM [FailureTable] as ft
INNER JOIN
(
select * from sysibm.systables
where CREATOR = 'SCHEMA'
and name like '%CUR%'
and type = 'T'
) st
ON st.[name] = ft.[tablename]
You can try
DECLARE #tableName VARCHAR(50);
SELECT #tableName = main
FROM xyx
EXEC('SELECT * FROM ' + 'dbo.' + #tableName)
Dont forget to add validation if #tableName doesnt get populated

Sorting Updated Columns In Sql Server

Hello good day everyone.
I have a table design in SQL server that looks like this:
NAME AGE WORK BIRTH
TEST 21 NONE 12/12/2000
In this table, I have created a trigger upon updating table and would save the data to audit log table. This audit log table holds the value being updated and the columns that has been update. I have a query snippet here that gets the columns that has been updated. I also get this query her on stack.
DECLARE #idTable INT
SELECT #idTable = T.id
FROM sysobjects P JOIN sysobjects T ON P.parent_obj = T.id
WHERE P.id = ##procid
-- Get COLUMNS_UPDATED if update
--
DECLARE #Columns_Updated VARCHAR(50)
SELECT #Columns_Updated = ISNULL(#Columns_Updated + ', ', '') + name
FROM syscolumns
WHERE id = #idTable
AND CONVERT(VARBINARY,REVERSE(COLUMNS_UPDATED())) & POWER(CONVERT(BIGINT, 2), colorder - 1) > 0
Now my audit log table looks like this:
OLD NEW COLUMNS_UPDATED
tEST,21,NONE TEST2,20,TEACHER AGE,NAME,WORK
Now my problem is, how I can sort the columns updated that looks like also the design table. My preferred output should look like this.
OLD NEW COLUMNS_UPDATED
tEST,21,NONE TEST2,20,TEACHER NAME,AGE,WORK
I hope anyone could help me with this.
Thanks.
Try:
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'myTable'
ORDER BY ORDINAL_POSITION

Filling a logical field on whether a record exists Oracle SQL

Right now I have:
UPDATE table_name
SET logical_field = 0
WHERE logical_field != 0
;
UPDATE table_name t
SET t.logical_field = 1
WHERE EXISTS
(SELECT 1
FROM other_table s
WHERE s.key_field = t.key_field)
AND t.logical_field != 1
;
This is a simplified version of my code. I want one statement that will set the logical based on the existence of another record and doesn't update it if it doesn't need to.
I've looked into 'decode' statements and I think that could work. Is decode the best for this or is there an easier way.
Using: Oracle 11g
I think I have the decode working. Let me know what you think and/or if there is a better way I'd like to learn it.
UPDATE table_name t
SET t.logical_field =
decode((SELECT distinct s.key_field
FROM other_table s
WHERE s.key_field = t.key_field), t.key_field, 1, 0)
WHERE t.logical_field !=
decode((SELECT distinct s.key_field
FROM other_table s
WHERE s.key_field = t.key_field), t.key_field, 1, 0)
;

Creating index if index doesn't exist

I have a problem creating an index with the advantage database server if it doesn't exist with a sql query.
My query looks like this:
If not Exists(<SELECT Query for amount of indizes for one column>) then
Create Index Test on Tablename (No); endif
So I don't use FullTextSearchIndizes,because it is a integer field. Otherwhise it would look like this:
If not Exists(SELECT * FROM tablename WHERE CONTAINS( * , 'Test' )) then
Create Index Test on Tablename (Name) Content; endif
So, my only problem is how do I get the indices. I've read in other DBMS you can use sys.indexes and some other things.
Take a look at the System tables:
https://devzone.advantagedatabase.com/dz/webhelp/Advantage10/devguide_system_tables.htm
In particular there is a table called system.indexes:
https://devzone.advantagedatabase.com/dz/webhelp/Advantage10/master_system_indexes.htm
Try something more like this, utilizing the system commands. This is a working example I use on an Advantage Database:
IF (SELECT Name FROM system.indexes
WHERE Index_File_Name = 'GLDept.adi'
AND Index_Expression = 'DeptNumber') IS NULL
THEN
EXECUTE PROCEDURE sp_CreateIndex90(
'GLDept',
'GLDept.adi',
'DEPTNUMBER',
'DeptNumber',
'',
2051,
512,
'' );
END IF;

Is it possible to tell SSMS not to check if a column exists in a t-sql script?

I tried to google it, but din't find a way
I have a t-sql script that adds a new column to a table, then fills that columns with values depending on some other columns in the same table and finally removes some columns. This all works fine.
The problem occures when I want to run the script again. I have a if clause that checks if the missing columns exists, but SSMS still complains and displays error messaged even though the code inside the if clause if not run. The script must be able to run more then once, and I don't want the error messages to be displayed!
In code (obviously test code, don't want to dump production code here...):
create table test (
Name text,
Switch int,
ValueA int,
ValueB int)
go
insert into test values ('Name', 0, 5, 10)
if not exists (select 1 from INFORMATION_SCHEMA.COLUMNS
where COLUMN_NAME = 'ValueC' and TABLE_NAME = 'test')
begin
alter table test
add ValueC int
end
go
-- This batch rasies error when run more then once!
if exists (select 1 from INFORMATION_SCHEMA.COLUMNS
where COLUMN_NAME = 'ValueA' and TABLE_NAME = 'test')
begin
update test
set ValueC = (select case Switch
when 0 then (select (ValueA - ValueB))
when 1 then (select (ValueB - ValueA))
end)
end
go
if exists (select 1 from INFORMATION_SCHEMA.COLUMNS
where COLUMN_NAME = 'ValueA' and TABLE_NAME = 'test')
begin
alter table test drop column ValueA
end
go
select * from test
--Name 0 10 -5
Here is the error message:
Msg 207, Level 16, State 1, Line 6
Invalid column name 'ValueA'.
Msg 207, Level 16, State 1, Line 7
Invalid column name 'ValueA'.
Cheers
--Jocke
Yes it is possible without dynamic SQL but with a bit of a kludgey workaround. I would just use EXEC for this.
The behaviour in SQL 2000 is explained here
Erland Sommarskog mentions "once all tables in a query exist, SQL Server performs full checks on the query."
So by adding a no-op reference in the query to a table that doesn't exist compilation can be deferred. With this adjustment the script below can be run multiple times without getting the error.
insert into test values ('Name', 0, 5, 10)
if not exists (select 1 from INFORMATION_SCHEMA.COLUMNS
where COLUMN_NAME = 'ValueC' and TABLE_NAME = 'test')
begin
alter table test
add ValueC int
end
go
create table #dummy
(i int)
-- This batch raised error when run more then once!
if exists (select 1 from INFORMATION_SCHEMA.COLUMNS
where COLUMN_NAME = 'ValueA' and TABLE_NAME = 'test')
begin
update test
set ValueC = (select case Switch
when 0 then (select (ValueA - ValueB))
when 1 then (select (ValueB - ValueA))
end) where not exists(select * from #dummy)
end
drop table #dummy
go
if exists (select 1 from INFORMATION_SCHEMA.COLUMNS
where COLUMN_NAME = 'ValueA' and TABLE_NAME = 'test')
begin
alter table test drop column ValueA
end
go
select * from test
--Name 0 10 -5
why don't you jsut use a temp table or variable table, add the last column to the declaration, and then you wouldn't have this problem?
I had this exact problem and the only thing that worked for me was to save the script. Close it. Then open it again in and run it in the query window.
Also, it looks like you have the proper GOs, but I found that if I was missing the GO after the check to add the column then not even re-opening the script worked.
Bit late to the party but I ran into this same scenario when trying to do conditional checks based on what version of SQL Server. I took the EXEC route mentioned above. In the below example as inline T-SQL, the SELECT against sys.tables would result in an invalid column name if ran on an earlier version of SQL Server that didn't have the column available.
To work around it, I put the SQL inside a variable and EXEC() it as part of a INSERT INTO to populate a table variable.
DECLARE #Status TABLE (
Result bit
)
DECLARE #Result bit
IF #SQLVer >= 11
SET #SQL='SELECT 1 FROM sys.tables WHERE object_id=' + CONVERT(varchar,#CurrTableObjID) + ' AND is_filetable=1'
DELETE FROM #Status
INSERT INTO #Status
EXEC (#SQL)
SELECT #Result=Result FROM #Status
IF IsNULL(#Result,0) = 1
BEGIN
PRINT 'Table ' + #CurrSchemaName + '.' + #CurrTableName + ' is a filetable'
SET #BadTables=1
END