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).
Related
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.
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.
I want to run a trigger each time a record is inserted or updated on table knowledgebase_messages which will vectorize the message column, using the joined pg_language_dictionary (e.g.: "French") for that message's locale_id.
Currently, the trigger working on row update, but not initial insert. Meaning, if I insert a row, then run a query to get records, updated the row in any way, or refresh the postgres UI, I see the vectorized value correctly there.
Trigger function:
runMessageVectorTriggerFn = 'CREATE OR REPLACE FUNCTION run_message_vector() ' +
'RETURNS TRIGGER ' +
'AS $BODY$ ' +
'BEGIN ' +
'IF pg_trigger_depth() <> 1 THEN ' +
'RETURN NEW; ' +
'END IF; ' +
'UPDATE knowledgebase_messages kbm ' +
'SET vector = to_tsvector(lang.pg_dictionary_name::regconfig, kbm.message) ' +
'FROM locales as loca ' +
'JOIN languages as lang ON loca.language_id = lang.id ' +
'WHERE kbm.locale_id = loca.id;' +
'RETURN NEW; ' +
'END; ' +
'$BODY$ LANGUAGE plpgsql';
Trigger:
runMessageVectorTrigger = 'CREATE TRIGGER run_message_vector AFTER INSERT OR UPDATE ON knowledgebase_messages ' +
'FOR EACH ROW EXECUTE PROCEDURE run_message_vector()';
When doing this in the BEFORE INSERT trigger, it doesn't update
the row being inserted because the row doesn't exist yet:
UPDATE knowledgebase_messages kbm...
Besides, it's not clear what is the intention in your UPDATE because
the WHERE clause seems to ignore the NEW row, as if it was implicit
that it was the target.
Anyway, instead of that, to change the row being inserted/updated, do
something along the lines of:
-- the SELECT must return 1 row, or in the worst case no row
-- otherwise an error will occur.
NEW.vector = (
SELECT
to_tsvector(lang.pg_dictionary_name::regconfig, NEW.message)
FROM locales as loca JOIN languages as lang
ON loca.language_id = lang.id
WHERE NEW.locale_id = loca.id
);
RETURN NEW;
both in BEFORE UPDATE and BEFORE INSERT cases.
Then you can remove this IF pg_trigger_depth() <> 1...
On this link
http://gallery.technet.microsoft.com/Compare-Data-0c5bfc87#content
we can find a stored procedure example which can compare two tables data. WHat I would like is to call this sp for each table in database. I have found next sp that will enumerate through all tables
http://weblogs.sqlteam.com/joew/archive/2007/10/23/60383.aspx
The problem is that I cannot get to pass properly parameters. Here is what I tried (I have placed both databases on local server):
Exec sp_MSforeachtable "EXEC sp_CompareTable dbName1, dbName2, NULL, PARSENAME('?', 1)"
and that fails with
Msg 102, Level 15, State 1, Line 1 Incorrect syntax near '[dbo].[Activities]'.
And the same message for every table. Can anyone help me with what I am doing wrong here?
I'll stick my neck out and post this as an answer because it's not formatted nicely as a comment.
Have you tried this:
sp_MSforeachtable "EXEC sp_CompareTable dbName1, dbName2, NULL, PARSENAME('[?]', 1)"
Update:
It looks like it doesn't like the PARSENAME. You could try this (I tried this on a version of sp_CompareTable with the EXEC changed to a PRINT).
Add this line to sp_CompareTable (before the EXEC):
SET #TableName = PARSENAME(#TableName,1)
Call it like this:
sp_MSforeachtable "EXEC sp_CompareTable dbName1, dbName2, dbo, '?'"
NB: This would be a quick fix for the case where you only have the "dbo" schema. It doesn't really answer the question of exactly why the original syntax doesn't work.
Update Again:
Here's a version of the Compare Table stored procedure which is tailored to run with sp_MSforeachtable
CREATE PROC [dbo].[uspCompareTable](#db1 varchar(250), #db2 sysname, #TableName sysname)
AS
declare #reason varchar(7)='Missing';
IF #TableName = '[dbo].[sysdiagrams]'
RETURN
IF CHARINDEX('.',#db1,1) <> 0
SET #db1=QUOTENAME(SUBSTRING(#db1,1, CHARINDEX('.',#db1,1)-1))+'.'+QUOTENAME(SUBSTRING(#db1, CHARINDEX('.',#db1,1)+1,DATALENGTH(#db1)-CHARINDEX('.',#db1,1)))
IF CHARINDEX('.',#db2,1) <> 0
SET #db2=QUOTENAME(SUBSTRING(#db2,1, CHARINDEX('.',#db2,1)-1))+'.'+QUOTENAME(SUBSTRING(#db2, CHARINDEX('.',#db2,1)+1,DATALENGTH(#db2)-CHARINDEX('.',#db2,1)))
EXEC ('
SELECT * FROM
(SELECT * FROM '+ #db1 + '.' + #TableName +'
EXCEPT
SELECT * FROM '+ #db2 + '.' + #TableName +') T
CROSS JOIN (SELECT '''+#reason +' in '+#db2 +'.' + #TableName+''' Reason) T2
UNION ALL
SELECT * FROM
(SELECT * FROM '+ #db2 + '.' + #TableName +'
EXCEPT
SELECT * FROM '+ #db1 + '.' + #TableName +' ) T
CROSS JOIN (SELECT ''' + #reason + ' in ' + #db1 + '.' + #TableName + ''' Reason) T2')
Here I'm assuming that schema will be part of the TableName (which it should be if you're calling from sp_MSforeachtable). Also a tweak to skip sysdiagrams which gets picked up on my system (SQL Server 2008 Express).
Usage would be
sp_MSforeachtable "EXEC uspCompareTable dbname1, dbname2, '?'"
How do I create a stored procedure that exists in one database but runs the below code against another (any) database?
SET #sql1 = N'INSERT INTO #Tables SELECT'
+ N' t.TABLE_NAME as TableName'
+ N',t.TABLE_SCHEMA as SchemaName'
+ N',(SELECT OBJECTPROPERTY(OBJECT_ID(t.TABLE_SCHEMA + ''.'' + t.TABLE_NAME),''TableHasIdentity'')) '
+ N'FROM ' + QUOTENAME(#TargetDBName)
+ N'.INFORMATION_SCHEMA.TABLES t'
IF #Verbose = 1
PRINT #sql1
EXEC(#sql1)
I get TABLE_NAME and SCHEMA_NAME successfully, but the main issue is that OBJECTPROPERTY() runs in the context of the stored procedure's database, not in the context of #TargetDBName. So, OBJECTPROPERTY() will always return null, unless #TargetDBName is the same as the database the sproc is in.
I am currently using SQL Server 2008.
Query the sys views directly like this
SELECT Tbl.name AS TableName, sch.name AS SchemaName,
HasIdentity = CASE WHEN EXISTS (SELECT * FROM your_target_db.sys.columns AS cols WHERE Tbl.object_id = cols.object_id and is_identity = 1) THEN 1 ELSE 0 END
FROM your_target_db.sys.tables AS Tbl INNER JOIN your_target_db.sys.schemas AS SCH ON Tbl.schema_id = Sch.schema_id
Could you instead use OPENQUERY (see here)?
Have you considered using IDENT_SEED in your dynamic query?
This will return the seed value of a table's identity column or NULL if one doesn't exist.
Example:
USE master
GO
CREATE DATABASE Test
GO
USE Test
GO
CREATE TABLE Test1 (ColA INT IDENTITY(100,1))
CREATE TABLE Test2 (ColA INT)
GO
USE master
GO
DECLARE #TargetDBName NVARCHAR(MAX), #sql1 NVARCHAR(MAX)
SET #TargetDBName = 'Test'
SET #sql1 = N'SELECT'
+ N' t.TABLE_NAME as TableName'
+ N',t.TABLE_SCHEMA as SchemaName'
+ N',(SELECT CASE WHEN IDENT_SEED('''
+ QUOTENAME(#TargetDBName) + '.''
+ t.TABLE_SCHEMA + ''.''
+ t.TABLE_NAME) IS NOT NULL THEN 1 ELSE 0 END) as HasIdentity '
+ N'FROM ' + QUOTENAME(#TargetDBName)
+ N'.INFORMATION_SCHEMA.TABLES t'
EXEC(#sql1)
GO
DROP DATABASE Test
GO
The results:
TableName SchemaName HasIdentity
---------- ----------- -----------
Test1 dbo 1
Test2 dbo 0
One caveat you may need to consider:
Returns NULL on error or if a caller
does not have permission to view the
object.