isql DECLARE statement to psql - sybase

I have a PostgreSQL DB and have a script which calculates dates from an old Sybase DB. How can I do the same thing is PostgreSQL ?
isql
DBCOMMAND="eval isql -d $DATABASE -U user -P passwd "
$DBCOMMAND << MSG > $LOG_MEM_EXCEP
DECLARE #PREVINTDATETIME DATETIME
select #PREVINTDATETIME=(DATEADD(hh, -24, GETDATE()))
DECLARE #CURDATE DATETIME
select CURDATE=GETDATE()
select XTIME, MESSAGE from EXCEPTION_ALERTS where (XTIME between #PREVINTDATETIME AND #CURDATE)
exit MSG

Basically it burns down to a simple SQL statement:
SELECT xtime, message
FROM exception_alerts
WHERE xtime BETWEEN now() - interval '1d' AND now();
.. returning two columns of all rows in table exception_alerts from the last 24 hours.
Did you want to make a sql or plpgsql function out of it? Or call it from the shell using the command line interface psql? What is the exact form you would expect in return? Including column names?

Related

How to suppress sql query output and show only the number of rows

I have the following powershell command which displays the number of rows in a sql table. This works but it also includes the header:
Invoke-Sqlcmd -ServerInstance "01-SQL1\INSTANCE22" -Database master -Query "select Count(*) from dbo.mytable"
The Output I get is:
Column1
-------
2450 <= This line is actually displayed under Column1 on a separate line. I just couldn't get it to display properly here.
The only output I need is to show me the row count if it's greater than X number of rows, otherwise print "Less than 5000 rows found." How do I do this?
You're trying to mix numbers with text, so your best bet is to return that value into a variable and then set a rule to display whatever you want: however, you can also accomplish this with pure SQL:
SELECT CASE
WHEN COUNT(*) < 5000 THEN
'Less than 5,000'
ELSE
CAST(COUNT(*) AS VARCHAR(10))
END
FROM [dbo].[myTable] ;
Select count(*) as totalcount from table
this should answer your question.
sqlcmd -S localhost -d master -Q "if ((select Count(*) from spt_values) < 5000) PRINT 'Less than 5000 rows found'"
ps version: just thew query that's different
Invoke-Sqlcmd -ServerInstance "localhost" -Database master -Query "if ((select Count(*) from spt_values) < 5000) PRINT 'Less than 5000 rows found'" -verbose

Copy result of SQL Server query to Excel

I'm trying to figure out a way to copy the result of a SQL Server query to Excel. I know that with PostgreSQL, you can execute the following command:
COPY (SELECT id, summary, description FROM table) TO 'C:/test/table.xls';
to achieve the desired result. What is the equivalent method in SQL Server?
And I want to run it as a query statement since I would like to automate this process by running the query with a batch file as a scheduled task.
Try this:
mysql -b -e "$MY_QUERY" > my_data.csv
and see this Q for ref and more detail
Convert mysql query results to CSV (with copy/paste)
Try this:
INSERT INTO
OPENROWSET (
'Microsoft.ACE.OLEDB.12.0',
'Excel 8.0;HDR=NO;Database=C:\test\table.xls;',
[Sheet1$]
)
SELECT id, summary, description FROM table
Some limitation
You must create empty excel file first.
You must add column names in first row appropriate with inserted data.
I figured it out, just use BCP (Bulk Copy Program) to do the job like this:
bcp "select * from [databasename].[dbo].[tablename]" queryout "c:\test\table.csv" -c -t"," -r"\n" -S servername -T

SQL bulk insert using bcp between servers through script without using linked server

SQL bulk insert using bcp between servers through script without using linked server.
I'm trying to use the following queries:
bcp AdventureWorks.dbo.BuildVersion out Currency.dat -U sa -P 123456 -c -[cespl-pc130]
bcp AdventureWorks.dbo.BuildVersion in Currency.dat -U sa -P 123456 -c -[cespl-pc83]
I am getting the following error:
Msg 102, Level 15, State 1, Line 1 Incorrect syntax near '.'.
Is it the right way to do?
Explain the possibilities to do the bulk data transfer between servers.
try this:
SELECT a.*
FROM OPENROWSET('SQLNCLI', 'Server=Seattle1;Trusted_Connection=yes;',
'SELECT col1,col2,col3..
FROM AdventureWorks.dbo.BuildVersion
) AS a;
Here you need to provide your server name from where you want to copy the data.And run this above query in your destination server.

SELECT query on a table with a space in the name using SQSH

I'm using SQSH (version 2.1) on Ubuntu 10.04 to connect to a MSSQL database using a command like this:
sqsh -S server -U user -P password -D database
I have a table called My Table, but I cannot find a way to run a SELECT query on it. This is what I've tried so far:
SELECT * FROM 'My Table'
go
Output: Incorrect syntax near 'My Table'. (I get the same for double quotes)
\set t="My Table"
SELECT * FROM $t
go
Output: Invalid object name 'My'. (Which is weird because if I do \echo $t, I get the full table name)
SELECT * FROM My\\ Table
go
Output: Invalid object name 'My'.
SELECT * FROM [My Table]
go
Output: Unicode data in a Unicode-only collation or ntext data cannot be sent to clients using DB-Library (such as ISQL) or ODBC version 3.7 or earlier.
This last command works fine for table names without any spaces.
UPDATE: other commands work fine e.g. I can get the table description with:
SELECT column_name,data_type FROM information_schema.columns WHERE table_name = 'My Table'
go
Putting the table name in quotes doesn't work in MS SQL Server.
The correct way is using [ ]:
SELECT * FROM [My Table]
Im using SQL 2008R2, and the following works for me
['table name']
Finally found the solution. I had to add the following 2 lines to /etc/freetds/freetds.conf
tds version = 8.0
client charset = UTF-8
Try setting QUOTED_IDENTIFIER to ON when using SQL Server. For more info about QUOTED_IDENTIFIER see: http://msdn.microsoft.com/en-us/library/ms174393.aspx

Mysql dump of single table

I am trying to make some normal (understand restorable) backup of mysql backup. My problem is, that I only need to back up a single table, which was last created, or edited. Is it possible to set mysqldump to do that? Mysql can find the last inserted table, but how can I include it in mysql dump command? I need to do that without locking the table, and the DB has partitioning enabled.... Thanks for help...
You can use this SQL to get the last inserted / updated table :-
select table_schema, table_name
from information_schema.tables
where table_schema not in ("mysql", "information_schema", "performance_schema")
order by greatest(create_time, update_time) desc limit 1;
Once you have the results from this query, you can cooperate it into any other language (for example bash) to produce the exact table dump).
./mysqldump -uroot -proot mysql user > mysql_user.sql
For dumping a single table use the below command.
Open cmd prompt and type the path of mysql like c:\program files\mysql\bin.
Now type the command:
mysqldump -u username -p password databasename table name > C:\backup\filename.sql
Here username - your mysql username
password - your mysql password
databasename - your database name
table name - your table name
C:\backup\filename.sql - path where the file should save and the filename.
If you want to add the backup table to any other database you can do it by following steps:
login to mysql
type the below command
mysql -u username -p password database name < C:\backup\filename.sql

Resources