#!/usr/bin/perl
use strict;
use DBI;
use Data::Dumper;
use Asterisk::AGI;
my $agi = new Asterisk::AGI;
my $extension = '8315';
my $cti = '7702009896';
my $service_id =1;
my $DSN = q/dbi:ODBC:SQLSERVER/;
my $uid = q/ivr/;
my $pwd = q/ivr/;
my $DRIVER = "Freetds";
my $dbh = DBI->connect($DSN,$uid,$pwd) or die "Coudn't Connect SQL";
my $sql3=(qq{
declare '#' + callnumber as int
set '#' + callnumber = $callnumber
set '#' + callnumber = (Select '#'+'#' + identity)
exec "insert into rpt_call_detail (call_start_time,call_number,call_service_id,call_step_name,call_step_type,call_step_discription) values(getdate(),'#' + callnumber,$service_id,'START',0,'CLI:' + $cli)"
});
my $call_insert1 = $dbh->prepare($sql3);
$call_insert1->execute();
How to set a sql server variable inside Perl script? I want to set callnumber as ##identity I'm not able execute above code successfully.Please help me.
declare '#' + callnumber as int is not valid (MS) SQL. You want it to say declare #callnumber as int instead, so after escaping the #, you end up with declare \#callnumber as int. I'm not familiar with using ##IDENTITY, but assuming that part is correct, your $sql3 variable would look like:
my $sql3=(qq{
declare \#callnumber as int
set \#callnumber = $callnumber
set \#callnumber = (Select \#\#identity)
exec "insert into rpt_call_detail (call_start_time,call_number,call_service_id,call_step_name,call_step_type,call_step_discription) values(getdate(),'#' + callnumber,$service_id,'START',0,'CLI:' + $cli)"
});
Related
In Snowflake, when I create a store proc like so
create procedure stack_overflow_question(select_table varchar)
returns varchar
language sql
as
declare
select_statement varchar;
begin
select_statement := '
SELECT * FROM ' || :select_table || '
';
end;
Then, later when I use select get_ddl('procedure', 'stack_overflow_question(varchar)'); function to make edits to the store proc, the result of this function call has extra single quotes.
Here is the result
CREATE OR REPLACE PROCEDURE "STACK_OVERFLOW_QUESTION"("SELECT_TABLE" VARCHAR(16777216))
RETURNS VARCHAR(16777216)
LANGUAGE SQL
EXECUTE AS OWNER
AS 'declare
select_statement varchar;
begin
select_statement := ''
SELECT * FROM '' || :select_table || ''
'';
end';
Note the difference between the two! The extra single quotes. Also double quotes in the name of the store proc.
Is there something that I can do to prevent this from happening? I am using Snowsight - but don't think that this actually is the problem. Also, I am using snowflake as the language for store procs.
Any ideas?
I wrote a UDF that you can wrap around get_ddl that will convert the DDL from using doubled single quotes to single quotes and wrap the body with $$:
create or replace function CODE_DDL_TO_TEXT(CODE_TEXT string)
returns string
language javascript
as
$$
var lines = CODE_TEXT.split("\n");
var out = "";
var startCode = new RegExp("^AS '$", "ig");
var endCode = new RegExp("^'\;$", "ig");
var inCode = false;
var isChange = false;
var s;
for (i = 0; i < lines.length; i++){
isChange = false;
if(!inCode) {
inCode = startCode.test(lines[i]);
if(inCode) {
isChange = true;
out += "AS $" + "$\n";
}
}
if (endCode.test(lines[i])){
out += "$" + "$;";
isChange = true;
inCode = false;
}
if(!isChange){
if(inCode){
s = lines[i].replace(/''/g, "'") + "\n";
s = s.replace(/\\\\/g, "\\");
out += s;
} else {
out += lines[i] + "\n";
}
}
}
return out;
$$;
You can then call the UDF by wrapping it around the get_ddl function. Here is an example of fishing its own DDL out of get_ddl:
select CODE_DDL_TO_TEXT(get_ddl('function', 'CODE_DDL_TO_TEXT(string)'));
Edit:
You can also use this SQL to reconstruct a stored procedure from the INFORMATION_SCHEMA:
select 'create or replace procedure ' || PROCEDURE_NAME || ARGUMENT_SIGNATURE ||
'\nreturns ' || DATA_TYPE ||
'\nlanguage ' || PROCEDURE_LANGUAGE ||
'\nas $' || '$\n' ||
PROCEDURE_DEFINITION ||
'\n$' || '$;'
from INFORMATION_SCHEMA.PROCEDURES
;
This only returns body -
SELECT PROCEDURE_DEFINITION
FROM INFORMATION_SCHEMA.PROCEDURES
WHERE PROCEDURE_SCHEMA = 'SCHEMA_NAME' AND PROCEDURE_NAME = upper('stack_overflow_question');
We prefer coding Snowflake stored procedures and javascript UDF's using the $$ notation. It is easier as we do not have to worry about escaping every single quote in our code. However, when we retrieve the DDL using GET_DDL, Snowflake removes the $$ and places the body of the SP in single quotes and also escapes every single quote.
Is there a way to get the SP DDL from Snowflake in the $$ format?
Example, below is the SP we create. Notice the $$ sign and that we do not hae
CREATE OR REPLACE PROCEDURE "SP_TEST"()
RETURNS VARCHAR(16777216)
LANGUAGE JAVASCRIPT
EXECUTE AS CALLER
AS $$
var result = snowflake.execute({sqlText: "select 'Hello World!' as test;"})
result.next();
return String(result.getColumnValue(1));
$$;
Then, when we retrieve the DDL from Snowflake using SELECT GET_DDL('PROCEDURE','SP_TEST()'), we get the following. Notice the $$ has been replaced by single quotes and that all other single quotes are now escaped.
CREATE OR REPLACE PROCEDURE "SP_TEST"()
RETURNS VARCHAR(16777216)
LANGUAGE JAVASCRIPT
EXECUTE AS CALLER
AS '
var result = snowflake.execute({sqlText: "select ''Hello World!'' as test;"})
result.next();
return String(result.getColumnValue(1));
';
Thanks
I've not found a built-in way to do it, but you can use a UDF to do this. This should work provided that the $$ start and end of the code section are always on lines by themselves:
create or replace function CODE_DDL_TO_TEXT(CODE_TEXT string)
returns string
language javascript
as
$$
var lines = CODE_TEXT.split("\n");
var out = "";
var startCode = new RegExp("^AS '$", "ig");
var endCode = new RegExp("^'\;$", "ig");
var inCode = false;
var isChange = false;
var s;
for (i = 0; i < lines.length; i++){
isChange = false;
if(!inCode) {
inCode = startCode.test(lines[i]);
if(inCode) {
isChange = true;
out += "AS $" + "$\n";
}
}
if (endCode.test(lines[i])){
out += "$" + "$;";
isChange = true;
inCode = false;
}
if(!isChange){
if(inCode){
s = lines[i].replace(/''/g, "'") + "\n";
s = s.replace(/\\\\/g, "\\");
out += s;
} else {
out += lines[i] + "\n";
}
}
}
return out;
$$;
select CODE_DDL_TO_TEXT(get_ddl('function', 'CODE_DDL_TO_TEXT(string)'));
execute immediate $$
DECLARE
PROCS RESULTSET;
ALL_PROCS RESULTSET;
DB_NAME STRING DEFAULT 'PROC_TEST';
TABLE_NAME STRING;
QUERY STRING;
ALL_QUERY STRING;
COUNT INT DEFAULT 0;
OUTPUT STRING DEFAULT '';
c1 CURSOR FOR select DATABASE_NAME from snowflake.information_schema.databases;
BEGIN
TABLE_NAME := CONCAT(DB_NAME, '.INFORMATION_SCHEMA.SCHEMATA');
OPEN c1;
FOR rec IN c1 DO
QUERY := 'SELECT PROCEDURE_CATALOG,PROCEDURE_NAME,PROCEDURE_OWNER,PROCEDURE_DEFINITION FROM ' || rec.DATABASE_NAME || '.INFORMATION_SCHEMA.procedures';
OUTPUT := OUTPUT || QUERY || '\n UNION ALL \n';
--PROCS := (EXECUTE IMMEDIATE :QUERY);
-- ALL_PROCS := ALL_PROCS + PROCS;
END FOR;
--ALL_PROCS := (EXECUTE IMMEDIATE :OUTPUT);
--RETURN table(ALL_PROCS);
RETURN OUTPUT;
END;
$$;
I have this code:
if($update[$entity_id])
{
my $sql = "UPDATE cache SET date = '?', value = '?' WHERE item_id = ? AND level = ? AND type = ?;";
}
else
{
my $sql = "INSERT INTO cache (date, value, item_id, level, type) VALUES ('?','?',?,?,?);";
}
my $db = $self->{dbh}->prepare(q{$sql}) or die ("unable to prepare");
$db->execute(time2str("%Y-%m-%d %X", time), $stored, $entity_id, 'entity', 'variance');
But when it want to run the update I get this error:
DBD::Pg::st execute failed : called with 5 bind variables when 0 are needed.
Why?
If you had turned on strict and/or warnings, you would see what your problem is.
You're writing
if (...) {
my $sql = ...;
} else {
my $sql = ...;
}
execute($sql);
Which means that the $sql variables that you declare in the if branches aren't in scope and you're trying to execute completely empty SQL.
You're preparing literal '$sql', but that is not your only problem, lexical $sql variables go out of scope outside {}.
Try,
use strict;
use warnings;
#...
my $sql;
if($update[$entity_id])
{
$sql = "UPDATE cache SET date = ?, value = ? WHERE item_id = ? AND level = ? AND type = ?";
}
else
{
$sql = "INSERT INTO cache (date, value, item_id, level, type) VALUES (?,?,?,?,?)";
}
my $st = $self->{dbh}->prepare($sql) or die ("unable to prepare");
$st->execute(time2str("%Y-%m-%d %X", time), $stored, $entity_id, 'entity', 'variance');
How can I update row in table in yii? I am using the following code but it is not working
$sql = "UPDATE auth_assignment SET itemname = 'Authenticated' WHERE userid = $user->accountID";
$command = $connection->createCommand($sql);
$command->execute();
My guess is that $user is being converted to a string and thus the ->accountID is not working. You have two methods, one unsafe and one safe.
Unsafe - Add {} around the $user->accountID.
$sql = "UPDATE auth_assignment SET itemname = 'Authenticated' WHERE userid = {$user->accountID}";
Safer - Use a parametrized query:
$sql = "UPDATE auth_assignment SET itemname = 'Authenticated' WHERE userid = :userid";
$command = $connection->createCommand($sql);
$command->execute(array(':userid' => $user->accountID))
ok I forgot to put commas around
'user->accountID'
In a data importing script:
client = TinyTds.Client.new(...)
insert_str = "INSERT INTO [...] (...) VALUE (...)"
client.execute(insert_str).do
So far so good.
However, how can I attach a .pdf file into the varbinary field (SQL Server 2000)?
I've recently had the same issue and using activerecord was not really adapted for what I wanted to do...
So, without using activerecord:
client = TinyTds.Client.new(...)
data = "0x" + File.open(file, 'rb').read.unpack('H*').first
insert_str = "INSERT INTO [...] (...) VALUE (... #{data})"
client.execute(insert_str).do
To send proper varbinary data, you need to read the file, convert it to hexadecimal string with unpack('H*').first and prepend '0x' to the result.
Here is PHP-MSSQL code to save binary data:
mssql_query("SET TEXTSIZE 2147483647",$link);
$sql = "UPDATE UploadTable SET UploadTable_Data = ".varbinary_encode($data)." WHERE Person_ID = '".intval($p_id)."'";
mssql_query($sql,$link) or
die('cannot upload_resume() in '.__FILE__.' on line '.__LINE__.'.<br/>'.mssql_get_last_message());
function varbinary_encode($data=null) {
$encoded = null;
if (!is_null($data)) {
$a = unpack("H*hex", $data);
$encoded = "0x";
$encoded .= $a['hex'];
}
return $encoded;
}
Here is PHP-MSSQL code to get binary data:
mssql_query("SET TEXTSIZE 2147483647",$link);
$sql = "SELECT * FROM UploadTable WHERE ID = 123";
$db_result = mssql_query($sql,$link);
// work with result like normal
I ended up using activerecord:
require 'rubygems'
require 'tiny_tds'
require 'activerecord-sqlserver-adapter'
..
my_table.create(:file_name => "abc.pdf", :file_data => File.open("abc.pdf", "rb").read)
For SQLServer 2000 support, go for 2.3.x version activerecord-sqlserver-adapter gem.