Issue Creating Several Scripts with Postgres - postgresql

I am using postgres to create several INSERT scripts to insert data from one database to another.
The statement is giving me an error for invalid syntax for integer.
Here is the script I am trying to run
select 'INSERT INTO public."HoldingMasters"(
"AccountID", "AssetID", "CreatedDate", "DateAcquired", "GainsLongTerm", "LotNumber", "Managed", "ModifiedDate", "Sweep", "UID", "Units", "UnitsPledged", "IsModified", "ModifiedCount")
SELECT ' + CAST("AccountID" as integer) + ',' + CAST("AssetID" as integer) + ',' + "CreatedDate" + ',' + "DateAcquired" + ',' + "GainsLongTerm" + ',' + CAST("LotNumber" as integer) + ',' + "Managed" + ',' + "ModifedDate" + ',' + "Sweep" + ',' + CAST("UID" as integer) + ',' + "Units" + ',' + ',' + "UnitsPledged" + ',' + "IsModifed" + ',' + CAST("ModifiedCount" as integer) +
'WHERE NOT EXISTS(SELECT "UID" from "HoldingMasters" where "UID" = ' + CAST("UID" as integer) +')'
as script from "HoldingMasters";
And this gives me the error:
ERROR: invalid input syntax for integer: "INSERT INTO public."HoldingMasters"(
"AccountID", "AssetID", "CreatedDate", "DateAcquired", "GainsLongTerm", "LotNumber", "Managed", "ModifiedDate", "Sweep", "UID", "Units", "UnitsPledged", "IsModified", "ModifiedCount")
SELECT "
LINE 1: select 'INSERT INTO public."HoldingMasters"(
^
SQL state: 22P02
Character: 8
Several of these columns are integers and I am not sure what syntax to use to get them to cast properly in the INSERT statement within my scripts.
I have tried:
SUM(NULLIF("AccountID", '')::integer)
"AccountID"::integer
to_number - does not seem to work on my machine
I have run this INSERT statement by itself without any issue, it just seems to have troubles when within the "as script" generator. I have not seen anyone try this syntax within a script generator.
Any help would be appreciated.

Related

How to insert into POSTGRESQL table mac-address from string value

I use a table with mac-address field.
Now I want to create an insert statement to insert mac address from my edit.
SQL Insert:
cInsertL2IfParams : string = 'INSERT INTO tb_macaddresses(fmacaddr) ' +
'VALUES(pMyMACAddress::macaddr)';
So:
mymacaddr := MainDM.MainSQLQ.Params.CreateParam(TFieldType.ftString,'pMyMACAddress',TParamType.ptInput);
mymacaddr.value := myedit.Text;
"Open" procedure rised exception: EPQDatabaseError... ...string contains NULL (10,null)
SQL State: 23502
...
I try to insert my string in the pgAdmin and I don't have any error:
INSERT INTO tb_macaddresses(fmacaddr)
VALUES('18:FD:74:7F:73:D3'::macaddr);
Found temporary variant. I removed TParam and insert ordinary text.
MainDM.MainSQLQ.SQL.Text := 'INSERT INTO tb_netifl2params(tb_netif_id, tb_netifl2params_mac, tb_netifl2params_adminmac) VALUES(:pL2NetIfID,' + '''' + edL2InterfaceMAC.Text + '''' + ',' + '''' + edL2AdminMAC.Text + '''' + ')';
tb_netifl2params_mac and tb_netifl2params_adminmac are MAC-address fields.
edL2InterfaceMAC.Text and edL2AdminMAC.Text string values from TEdit.

Getting "Conversion Failed" Error in SQl Server

Unknown error in Dynamic String Handling in a T-SQL Environment. PS: I am not going to do any conversions. Just want to create an Update statement and execute it later
Code:
DROP TABLE IF EXISTS #TEMP
Select 'CRDB_Reporting' tablename,'MagnitudePackage' updatecolumn,'String' updatecolumntype,'''XLFWH''' updatevalue,'NatureOfFundCode' primaryfilter,'String' primaryfiltertype,'''FWH''' primaryfiltervalue,NULL remainingfilter
INTO #TEMP
Select
CASE
WHEN remainingfilter IS NOT NULL THEN
'Update [dbo].[' + tablename +'] Set [' + updatecolumn +'] = ' + updatevalue + ' Where [' + primaryfilter +'] = ' + primaryfiltervalue + ' And ' + remainingfilter
WHEN remainingfilter IS NULL THEN
'Update [dbo].[' + tablename +'] Set [' + updatecolumn +'] = ' + updatevalue + ' Where [' + primaryfilter +'] = ' + primaryfiltervalue + ' And '
END
From #Temp
Expected Result
Update [dbo].[CRDB_Reporting] Set [MagnitudePackage] = 'XLFWH' Where [NatureOfFundCode] = 'FWH'
Error Msg:
Msg 245, Level 16, State 1, Line 34 Conversion failed when converting
the varchar value 'Update [dbo].[CRDB_Reporting] Set
[MagnitudePackage] = 'XLFWH' Where [NatureOfFundCode] = 'FWH' And '
to data type int.
When you are creating the column remainingfilter it has an implicit conversion of int
So to fix that, use ...,cast(NULL as varchar(max)) remainingfilter
That said, I would opt for concat()
Example
Select Cmd = concat('Update ',quotename(tablename),' set ',quotename(updatecolumn),' = ',updatevalue,' And ' + nullif(remainingfilter,''))
From #Temp
Returns
Update [CRDB_Reporting] set [MagnitudePackage] = 'XLFWH'

Problem trying to set a column value in a temp table to an empty string

Currently in an SP, we have columns created in a temp table that are being set to 0 by default using the first SET statement below but I am now needing the columns to be set to an empty string value and not null:
SET #columns = #columns + ',' + CHAR(13) + CHAR(10) + ' [' + cast((#i+1) as nvarchar) + '] int Default 0' SET #i = #i + 1;
I tried using this solution:
SET #columns = #columns + ',' + CHAR(13) + CHAR(10) + ' [' + cast((#i+1) as nvarchar) + '] nvarchar Default []' SET #i = #i+1;
but when I create the ALTER statement:
Alter TABLE #Survivaltmp Add ' + STUFF(#columns, 1, 1, '') + ''
that adds the column with stuffing this variable I am getting this error:
An object or column name is missing. For Select Into statements verify each column has a name.
My question is, is there any way to add an empty string value to a column? Any help/direction would be appreciated. Thanks.
Strings are enclosed in single quotes, not brackets, they're for identifiers.
Try:
... + '] nvarchar Default ''''' ...

execute sql DDL WITH ibscript at runtime

I have a problem about running script
IBScript := TIBScript.Create(nil);
IBScript.Database := FDM_DB.IBD_GCV;
IBScript.Transaction := FDM_DB.IBT_GCV;
IBScript.Terminator := ';';
IBScript.AutoDDL:=true;
IBScript.Script.Clear;
IBScript.Script.Add('GRANT INSERT, UPDATE ON ' + table_name + ' TO ' + user + ' ;');
IBScript.ExecuteScript;
IBScript.Transaction.CommitRetaining;
strong textit shows me this message
'Dynamic SQL Error SQL error code = -104 Token unknown - line 1,
column 43 TO'.
thank you in advance
You have
GRANT INSERT, UPDATE ON ' + table_name + ' TO ' + user + ;
sql only.
So, check 'table_name' variable value.
This error can occur when:
table_name = '';//(empty string).

Export query to text file

What I am trying to do is export a Tsql query to a csv file. Simple enough, however I need to be able to specify which fields are wrapped in quotes "". I can get my query to export with all the feilds wrapped.
"SCHEN001","Joe Bloggs Inc","1","1","1","1","1","1","13","6","Mr John Smith"
What I would like to export is
"SCHEN001","Joe Bloggs Inc",1,1,1,1,1,1,13,6,"Mr John Smith"
Is this possible using Tsql?
Any ideas would be greatly appreciated
Take a look at the bcp.exe utility. It is ment for bulk operations and you can specify templates for exports etc.
A link that seems reasonable: http://www.simple-talk.com/sql/database-administration/creating-csv-files-using-bcp-and-stored-procedures/
Another approach is to use SQL Server Integration Services (if you have MS SQL Server Standard or Enterprise edition)
or, alternatively, you can copy grid results into Excel, and export CSV from there :-)
Try to use this script.
Set variable #TblName to the name of your table.
The script uses information_schema.columns
to get the datatypes for every column in selected table.
DECLARE #TblName varchar(128)
DECLARE #WhereClause varchar(255)
DECLARE #cmd varchar(7000)
SET #TblName = '<YOUR TABLENAME>' --TABLENAME
SET #cmd = ''
create table #tableDef (id int identity (1,1), ColType int, ColName varchar(128))
--Fetch table information
insert #tableDef (ColType, ColName)
select case when DATA_TYPE like '%char%' then 1
when DATA_TYPE like '%datetime%' then 2
else 0 end ,
COLUMN_NAME
from information_schema.columns
where TABLE_NAME = #TblName
order by ORDINAL_POSITION
SELECT #cmd = #cmd
+ ' CASE WHEN ' + ColName + ' IS NULL '
+ ' THEN ''NULL'' '
+ ' ELSE '
+ case ColType
when 1 then ''''''''' + ' + ColName + ' + '''''''''
when 2 then ''''''''' + ' + 'CONVERT(VARCHAR(20),' + ColName + ')' + ' + '''''''''
else 'CONVERT(VARCHAR(20),' + ColName + ')' end
+ ' END + '','' + '
from #tableDef
order by id
select #cmd = 'SELECT ' + left(#cmd,len(#cmd)-8) + '+'''' FROM ' + #tblName
exec (#cmd)
drop table #tableDef