The following code gives me the value of Fri Aug 06 2021 12:16:27 GMT-0700 (Pacific Daylight Time) instead of mm/dd/yyyy hh:mm:ss. What am I missing here? Please advise
create or replace procedure Load_Employee()
returns varchar not null
language javascript
EXECUTE AS CALLER
as
$$
//Variable Initialization
var IntegrationTable ='EMPLOYEE';
var TypeID=0;
var MaxDate=' ';
var cmd = "Select max(COMPLETED_DATE) from SCHEMA.TABLE where TARGET_TABLE_NAME= " + "'" + IntegrationTable + "'" ;
var sql = snowflake.createStatement({sqlText: cmd});
var result = sql.execute();
result.next();
MaxDate=result.getColumnValue(1);
return MaxDate;
$$
;
That's how JavaScript will render a date when presented as a string. You can change to YYYY-MM-DD like this:
create or replace procedure Load_Employee()
returns varchar not null
language javascript
EXECUTE AS CALLER
as
$$
//Variable Initialization
var IntegrationTable ='EMPLOYEE';
var TypeID=0;
var MaxDate=' ';
var cmd = "Select max(COMPLETED_DATE) from SCHEMA.TABLE where TARGET_TABLE_NAME= " + "'" + IntegrationTable + "'" ;
var sql = snowflake.createStatement({sqlText: cmd});
var result = sql.execute();
result.next();
MaxDate=formatDate(result.getColumnValue(1));
return MaxDate;
// Helper functions
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
hour = '' + d.getHours(),
minute = '' + d.getMinutes(),
second = '' + d.getSeconds(),
year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
if (hour.length < 2) hour = "0" + hour;
if (minute.length < 2) minute = "0" + minute;
if (second.length < 2) second = "0" + second;
return [month, day, year].join('/') + " " + [hour,minute,second].join(':');
}
$$
;
Related
I have a stored procedure to grant access to the Snowflake database table / views, the procedure compiled successfully but getting the below error while executing:
Step1:
What I am trying to do is select the records from the database table having the below column:
"select PRIVILEGE, GRANTED_ON,NAME, GRANTED_TO,GRANTEE_NAME,TABLE_CATALOG, TABLE_SCHEMA, MODIFIED_ON from USERS_GRANTS_TO_ROLE_TBL" ;
Step2:
Get the values into the vairables, form a Grant syntax like below:
`GRANT ` + return_privilege + ` ON ` + return_granted_on + ` ` + return_table_catelog + `.` + return_table_schema + `.` + return_name + ` TO ` + return_granted_to + ` ` + return_grantee_name ;
Step3:
Insert the data into below table having columns as below:
"INSERT INTO TEST_GRANTS_TO_ROLE_SCRIPTS_TBL VALUES (" + return_table_catelog + "," + return_modified_on + "," + " " + sql_statement + ";" + " " + ")";
The below error encountered when I call the Stored Proc written using javascript language.
SQL Error [1003] [42000]: Execution error in store procedure
SAMPLE_TEST_USER_GRANTS: SQL compilation error: syntax error line 1 at
position 60 unexpected 'May'. syntax error line 1 at position 115
unexpected 'GRANT'. At Statement.execute, line 46 position 20
Appreciate, if anyone can help me out with this.
var VAR_SQL_STMT = "select PRIVILEGE, GRANTED_ON,NAME,
GRANTED_TO,GRANTEE_NAME,TABLE_CATALOG,
TABLE_SCHEMA, MODIFIED_ON
from USERS_GRANTS_TO_ROLE_TBL" ;
var stmt = snowflake.createStatement( { sqlText: VAR_SQL_STMT } );
/* Creates result set */
var res = stmt.execute();
while (res.next()) {
var return_privilege = res.getColumnValue(1);
var return_granted_on = res.getColumnValue(2);
var return_name = res.getColumnValue(3);
var return_granted_to = res.getColumnValue(4);
var return_grantee_name = res.getColumnValue(5);
var return_table_catelog = res.getColumnValue(6);
var return_table_schema = res.getColumnValue(7);
var return_modified_on = res.getColumnValue(8);
var sql_statement = GRANT + return_privilege + ` ON ` +
return_granted_on + ` ` + return_table_catelog + . +
return_table_schema + . + return_name + ` TO ` +
return_granted_to + ` ` + return_grantee_name ;
var var_sql_text = "INSERT INTO TEST_GRANTS_TO_ROLE_SCRIPTS_TBL
VALUES (" + return_table_catelog + "," + return_modified_on +
"," + " " + sql_statement + ";" + " " + ")";
var stmt1 = snowflake.createStatement( { sqlText: var_sql_text } );
stmt1.execute();
In your definition of var sql_statement you are missing quotes round a number of strings e.g. GRANT and the periods. It should look something like this:
var sql_statement = 'GRANT ' + return_privilege + ' ON ' +
return_granted_on + ' ' + return_table_catelog + '.' +
return_table_schema + '.' + return_name + ' TO ' +
return_granted_to + ' ' + return_grantee_name ;
There are multiple issues,The issue was Insert is failing for Date field coming in
a incorrect format. Added the below to the insert dynamic script as below:
return_modified_on date column toISOString()
"INSERT INTO TEST_GRANTS_TO_ROLE_SCRIPTS_TBL VALUES"
+ "(" + " " + "'" + return_table_catelog + "'"+ "," + "'"
+ return_modified_on.toISOString() + "'"+ "," + "'"
+ sql_statement + "'"+ ")" +";";
I am trying to view the data based on the current logged in user and group them together based on current month by using the group by() and datepart() method. However, it seems that my "" is incorrect. May I know what is the proper way of doing it? Thank you.
Below are my error and the codes:
E/Error: Invalid SQL statement or JDBC escape, terminating ''' not found.
val sqlCon = SQLCon()
val current = LocalDateTime.now()
val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
val formatted = current.format(formatter)
val sql : String=
"SELECT Category,eAmount,eNote,eDate FROM Expenses where Username = '" + cUser + "'" +
"AND eMonth = DATEPART(MONTH,'" + formatted + ")'" +
"AND eYear = DATEPART(YEAR,'" + formatted + ")'"
statement = connection!!.createStatement()
var rs : ResultSet = statement!!.executeQuery(sql)
while (rs.next())
{
var note : String = rs.getString("iNote") ?: ""
eList.add(ItemList(rs.getString("iCategory"), rs.getDouble("iAmount"),note,rs.getString("iDate")))
}
rs.close()
statement!!.close()
Toast.makeText(this, "Success", Toast.LENGTH_LONG).show()
I am new to SSIS. What I am trying to do. I have some text files in a folder. I want to get data from those files and load into sql server. I am using Script Task. Here's my code.
public void Main()
{
string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
try
{
//Declare Variables
string SourceFolderPath = Dts.Variables["User::SourceFolder"].Value.ToString();
string FileExtension = Dts.Variables["User::FileExtension"].Value.ToString();
string FileDelimiter = Dts.Variables["User::FileDelimiter"].Value.ToString();
string ArchiveFolder = Dts.Variables["User::ArchiveFolder"].Value.ToString();
string ColumnsDataType = Dts.Variables["User::DataType"].Value.ToString();
string SchemaName = Dts.Variables["User::SchemaName"].Value.ToString();
//string ColumnList = "";
SqlConnection myADONETConnection = new SqlConnection();
myADONETConnection = (SqlConnection)
(Dts.Connections["PLEGO.OwyheePrac1"].AcquireConnection(Dts.Transaction) as SqlConnection);
//Reading file names one by one
string[] fileEntries = Directory.GetFiles(SourceFolderPath, "*" + FileExtension);
foreach (string fileName in fileEntries)
{
//Writing Data of File Into Table
string TableName = "";
int counter = 0;
string line;
string ColumnList = "";
//MessageBox.Show(fileName);
System.IO.StreamReader SourceFile =
new System.IO.StreamReader(fileName);
while ((line = SourceFile.ReadLine()) != null)
{
if (counter == 0)
{
ColumnList = "[" + line.Replace(FileDelimiter, "],[") + "]";
TableName = (((fileName.Replace(SourceFolderPath, "")).Replace(FileExtension, "")).Replace("\\", ""));
string CreateTableStatement = "IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[" + SchemaName + "].";
CreateTableStatement += "[" + TableName + "]')";
CreateTableStatement += " AND type in (N'U'))DROP TABLE [" + SchemaName + "].";
CreateTableStatement += "[" + TableName + "] Create Table " + SchemaName + ".[" + TableName + "]";
CreateTableStatement += "([" + line.Replace(FileDelimiter, "] " + ColumnsDataType + ",[") + "] " + ColumnsDataType + ")";
SqlCommand CreateTableCmd = new SqlCommand(CreateTableStatement, myADONETConnection);
CreateTableCmd.ExecuteNonQuery();
//MessageBox.Show(CreateTableStatement);
}
else
{
string query = "Insert into " + SchemaName + ".[" + TableName + "] (" + ColumnList + ") ";
query += "VALUES('" + line.Replace(FileDelimiter, "','") + "')";
// MessageBox.Show(query.ToString());
SqlCommand myCommand1 = new SqlCommand(query, myADONETConnection);
myCommand1.ExecuteNonQuery();
}
counter++;
}
SourceFile.Close();
//move the file to archive folder after adding datetime to it
File.Move(fileName, ArchiveFolder + "\\" + (fileName.Replace(SourceFolderPath, "")).Replace(FileExtension, "") + "_" + datetime + FileExtension);
Dts.TaskResult = (int)ScriptResults.Success;
}
}
catch (Exception exception)
{
// Create Log File for Errors
using (StreamWriter sw = File.CreateText(Dts.Variables["User::LogFolder"].Value.ToString()
+ "\\" + "ErrorLog_" + datetime + ".log"))
{
sw.WriteLine(exception.ToString());
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
}
I am getting this error:
There are fewer columns in the INSERT statement than values specified in the VALUES clause.
I think this is because in source file. some rows has null values. Below is the example
ID, Name, LastName,ContactNumber
1,'abc','yuy',09090
2,,'wxz','4535
3,,,'7565
This is my original code:
String sqlQuery = "SELECT * FROM data where company = '"+ Selecteditem +"'" ;
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.rawQuery(sqlQuery, null);
if (c.moveToFirst()){
do{
temp_array.add(c.getString(c.getColumnIndex("name")) +
"," + c.getString(c.getColumnIndex("code")) +
"," + c.getString(c.getColumnIndex("company"))
);
I want to hide company on the list, I change "*" to name, code but without success, I delete " **"," + c.getString(c.getColumnIndex("company"))** " this line no success,
What to do please help me
You can just remove the company string, by replacing c.getString(c.getColumnIndex("company")) with an empty string "".
String sqlQuery = "SELECT * FROM data where company = '" + Selecteditem + "'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.rawQuery(sqlQuery, null);
if (c.moveToFirst()) {
do {
temp_array.add(c.getString(c.getColumnIndex("name")) +
"," + c.getString(c.getColumnIndex("code")) +
"," + ""
);
Another solution is to select only the columnn you need:
String sqlQuery = "SELECT name, code FROM data where company = '" + Selecteditem + "'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.rawQuery(sqlQuery, null);
if (c.moveToFirst()) {
do {
temp_array.add(c.getString(c.getColumnIndex("name")) +
"," + c.getString(c.getColumnIndex("code"))
);
I am working on an automation system in VB, and the project is in it's final stage.
I am working on report generation.The problem I am facing is, I want to create a full year report based on Class of students. How ever when the report is generated I only see the name of the first student in the record in the report or the last if I use a loop.
Just for information, I am using ADODB with Access Database, and Using ADODB.RecordSet to read data.
My Report generation part looks like as follows :
Set RS1 = New ADODB.recordSet
RS1.Open "SELECT * FROM RECORDS WHERE sClass = '" & ClassBox.Text & "';", connection, 3, adLockOptimistic
If Not RS1.EOF Then
Set DataReport2.DataSource = RS1.DataSource
End If
RS1.MoveFirst
Do Until RS1.EOF
DataReport2.Sections("Section1").Controls("NameLbl").Caption = CStr(RS1!sName)
DataReport2.Sections("Section1").Controls("SectionLbl").Caption = CStr(RS1!sSection)
DataReport2.Sections("Section1").Controls("ClassLbl").Caption = CStr(RS1!sClass)
DataReport2.Sections("Section1").Controls("JanLbl").Caption = CStr(RS1!January)
DataReport2.Sections("Section1").Controls("FebLbl").Caption = CStr(RS1!February)
DataReport2.Sections("Section1").Controls("MarLbl").Caption = CStr(RS1!March)
DataReport2.Sections("Section1").Controls("AprLbl").Caption = CStr(RS1!April)
DataReport2.Sections("Section1").Controls("MayLbl").Caption = CStr(RS1!May)
DataReport2.Sections("Section1").Controls("JunLbl").Caption = CStr(RS1!June)
DataReport2.Sections("Section1").Controls("JulLbl").Caption = CStr(RS1!July)
DataReport2.Sections("Section1").Controls("AugLbl").Caption = CStr(RS1!August)
DataReport2.Sections("Section1").Controls("SepLbl").Caption = CStr(RS1!September)
DataReport2.Sections("Section1").Controls("OctLbl").Caption = CStr(RS1!October)
DataReport2.Sections("Section1").Controls("NovLbl").Caption = CStr(RS1!November)
DataReport2.Sections("Section1").Controls("DecLbl").Caption = CStr(RS1!December)
DataReport2.Sections("Section1").Controls("TotalLbl").Caption = CStr(Val(RS1!January) + Val(RS1!February) + _
Val(RS1!March) + Val(RS1!April) + Val(RS1!May) + Val(RS1!June) + Val(RS1!July) + Val(RS1!August) + _
Val(RS1!September) + Val(RS1!October) + Val(RS1!November) + Val(RS1!December))
RS1.MoveNext
Loop
DataReport2.Show
What I want is to create the reports, where the report contains the names and details of the students sequentially based on my search criteria which is this case is class.
You can try modifying your existing code. If your controls have a DataField (it will depend on the control used), you can try setting that instead of the Caption property. I also modified your query to add a SUM(January, ...) field. I believe you could also add a formula field in in the report to do this if you prefer that method. I only added the line continuation so the query didn't scroll forever to the right.
Set RS1 = New ADODB.recordSet
RS1.Open "SELECT sName, sSection, sClass, January, February, March, April, " _
& "May, June, July, August, September, October, November, December, " _
& "(January + February + March + April + May + " _
& "June + July + August + September + October + " _
& "November + December) AS MonthTotal FROM RECORDS " _
& "WHERE sClass = '" & ClassBox.Text & "'", connection, 3, adLockOptimistic
' RS1.MoveFirst - not needed
DataReport2.Sections("Section1").Controls("NameLbl").DataField = "sName"
DataReport2.Sections("Section1").Controls("SectionLbl").DataField = "sSection"
DataReport2.Sections("Section1").Controls("ClassLbl").DataField = "sClass"
DataReport2.Sections("Section1").Controls("JanLbl").DataField= "January"
DataReport2.Sections("Section1").Controls("FebLbl").DataField = "February"
DataReport2.Sections("Section1").Controls("MarLbl").DataField = "March"
DataReport2.Sections("Section1").Controls("AprLbl").DataField = "April"
DataReport2.Sections("Section1").Controls("MayLbl").DataField = "May"
DataReport2.Sections("Section1").Controls("JunLbl").DataField = "June"
DataReport2.Sections("Section1").Controls("JulLbl").DataField = "July"
DataReport2.Sections("Section1").Controls("AugLbl").DataField = "August"
DataReport2.Sections("Section1").Controls("SepLbl").DataField = "September"
DataReport2.Sections("Section1").Controls("OctLbl").DataField = "October"
DataReport2.Sections("Section1").Controls("NovLbl").DataField = "November"
DataReport2.Sections("Section1").Controls("DecLbl").DataField = "December"
DataReport2.Sections("Section1").Controls("TotalLbl").DataField = "MonthTotal"
If Not RS1.EOF Then
Set DataReport2.DataSource = RS1
DataReport2.Show
End If