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

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.

Related

SQL Server 2012: Dynamic crosstab in stored procedure

Im trying to use a stored procedure to create a pivot table between two declared variables #rvar (as rowvariable) and #cvar (as columnvariable). The point is to call the stored procedure from VBA using these two as dynamic input when executing the stored procedure.
My code has three parts:
creating test-data
declaring locals
finding names of columns in crosstab an storing in new local #sql1
executing crosstable with the pivotfunction using the names stored in #sql1.
My problem: The code below works but I would like to make it dynamic regarding the variable defining the column structure - currently set to "q10_1_resp" - so that I only have to declare the local #cvar and use that in part 3 (like in part 4). I have succeeded in making part 3 into a sql-string with subsequent execution but then the column names stored in #sql1 cannot be used in the code in part 4 (I guess it is a scope thing).
--Part 1
create table [user].[test]
(rowvar nvarchar(max),
q10_1_resp int,
q10_2_resp int)
GO
INSERT [user].[test]
VALUES ('PH',1,2),
('PH',2,3),
('EA',1,5),
('EA',5,4),
('PH',3,4),
('PH',6,6),
('EA',4,1),
('PH',5,3),
('PH',2,1)
GO
-- Part 2
declare #rvar as nvarchar(max) = 'rowvar'
declare #cvar as nvarchar(max) = 'q10_1_resp' --this input should be dynamic as well
declare #sql1 as nvarchar(max)= ''
declare #sql2 as nvarchar(max)= ''
-- Part 3
select #sql1 = #sql1 + [a].[col] + char(44)
from
(select distinct QUOTENAME(q10_1_resp) as [col]
from [user].[test]
group by q10_1_resp) as a
SET #sql1 = left(#sql1, len(#sql1) - 1)
-- Part 4
SET #sql2 = 'select ' +
+ #rvar + ','
+ #sql1
+ ' from (Select '
+ #rvar + ', '
+ #cvar
+ ' from [user].[test]) sq pivot(count('
+ #cvar
+ ') for '
+ #cvar + ' IN ('
+ #sql1
+ ')) as pt'
exec sp_executesql #sql2
After a great deal of trying to globalize the scalarvariable without success using a temporary table to store the string was the key. The temporary table created at the beginning of the stored procedure can be assigned and referenced the entire time of the procedure. Thus assigning within execution of #sql and then referencing the string at execution of #sql2. I hope it makes sense.
CREATE PROCEDURE [dbo].[sp_crosstab]
-- Add the parameters for the stored procedure here
#rvar nvarchar(max) = '',
#cvar nvarchar(max) = '',
#data nvarchar(max) = '',
#sql nvarchar(max) = '',
#sql2 nvarchar(max) = '',
#sql3 nvarchar(max)=''
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
create table #temp_crosstab
(
sqlstr nvarchar(max)
)
set #sql ='
declare #sql1 nvarchar(max) = char(00)
select #sql1 = #sql1 + [a].[col] + char(44)
from
(select distinct QUOTENAME(' + #cvar + ') as [col]
from ' + #data + '
group by ' + #cvar + ') as a
SET #sql1 = left(#sql1, len(#sql1) - 1)
insert into #temp_crosstab values (#sql1)'
execute sp_executesql #sql
select #sql3 = [sqlstr] from #temp_crosstab
set #sql2 = '
select ' + #rvar + char(44) +
#sql3 + 'from (Select '
+ #rvar + char(44) + ' '
+ #cvar
+ ' from ' + #data + ') sq pivot(count('
+ #cvar
+ ') for '
+ #cvar + ' IN ('+#sql3+')) as pt'
exec sp_executesql #sql2
END
GO

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 ''''' ...

Dynamic SQL Query to Drop table

Looking for way to create some dynamic SQL to drop a table if it exists. However I can not seem to get the syntax correct. Here is the query so far (renamed fields for security)
DECLARE #TableNameNew NVARCHAR(MAX)
DECLARE #DynamicSQL2 NVARCHAR(MAX)
SET #TableNameNew = (SELECT 'tbl1_' + REPLACE(StaffCode,'.','') AS TableName
FROM tblEmployee WHERE (PCLogin = REPLACE(SYSTEM_USER, 'DOMAIN\', '')))
SET #DynamicSQL2 = 'IF OBJECT_ID(' + '''' + #TableNameNew + '''' + +','+'''U''' + ') IS NOT NULL DROP TABLE ' + #TableNameNew
EXEC #DynamicSQL2
This returns an error:
Could not find stored procedure 'IF OBJECT_ID('tbl1_ghewitt','U') IS NOT NULL DROP TABLE tbl1_ghewitt'.
Try
EXECUTE sp_executesql #DynamicSQL2
instead of
EXEC #DynamicSQL2

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