carriage return on mssql output in bat file - sql-server

so I am trying to get both mssql fields to output on separate lines but can not seem to figure out the proper command to implement this effect
I am currently using a , seperator but need the fields to be on separate lines in the TXT output file
so instead of abc,def I need
abc
def
this is what I am currently using
sqlcmd -S .\database -U sa -P password1 -d family -Q "select name, age from setup" -s"," -w -h -1 -o "C:\familysave.txt"

You can use ROW_NUMBER to calculate that result. That is my approach:
-- Step 1: create rownumber into #temp
select
ROW_NUMBER() OVER(ORDER BY name ASC) AS Row,
name, age into #temp from setup
--- Step 2: Join tables and using rownumber * 10 and 11 to get new order
SELECT name
FROM
(
select
Row * 10 as Row,
name from #temp
union
select
row * 11 , cast(age as varchar(100))
from #temp
) T order by row
Results
name
Carlos
25
Cecilia
21
Juan
20
Maria
22
Sample data
insert into setup values ('Juan', 20)
insert into setup values ('Carlos', 25)
insert into setup values ('Maria', 22)
insert into setup values ('Cecilia', 21)
Happy coding.
PS: Create SQL into Store Procedure to run from sqlcmd using EXEC SP_NAME
Tested on:
select ##VERSION
Microsoft SQL Server 2016 (SP2-GDR) (KB4583460) - 13.0.5108.50 (X64) May 20 2022 20:28:29 Copyright (c) Microsoft Corporation Web Edition (64-bit) on Windows Server 2019 Standard 10.0 (Build 17763: ) (Hypervisor)

Related

why only first 1000 records inserted in dbeaver?

I am using Dbeaver 22.1.4 on Windows 10 Home Single 64bit. My RAM is 8 Gb. I want to insert 16 millions data from one server to another using dblink (All servers are Linux Ubuntu, running Postgresql 12). The query looks like this ( I split it to 5000 first for testing) :
INSERT INTO table_server1 ([some 115 columns])
SELECT *
FROM dblink('myconn',$MARK$
SELECT [some 115 columns]
FROM public.table_server2 limit 5000
$MARK$) AS t1 (
id varchar, col1 varchar, col2 varchar, col3 integer, ... , col115 varchar);
It only inserts 1000 data which takes 1-2 seconds. It says "Updated rows : 1000" on the result window. There is no error as such.
What happen ? How can I insert all data ? I have edit the config file by modifying the max memory to 2 GB : -Xmx2048m
do you insist on using Dbeaver and/or dblink? If not, and you can connect to terminal on either postgres server, you can do this very fast (no splitting needed) and easily without "middle man" (your machine), directly server-to-server:
psql -d sourcedb -c "\copy (SELECT [some 115 columns] FROM public.table_server2) TO STDOUT" | psql -d targetdb -c "\copy table_server1 FROM STDIN"
Of course you need to specify host, user/password for both sides psql

Msg 601... "Could not continue scan with NOLOCK due to data movement".BUT NOLOCK ! - BUG

Strange situation... New physical severs, new install of SQL Server 2019 Enterprise version :
Microsoft SQL Server 2019 (RTM) - 15.0.2000.5 (X64) Sep 24 2019 13:48:23 Copyright (C) 2019 Microsoft Corporation Enterprise Edition: Core-based Licensing (64-bit) on Windows Server 2019 Standard 10.0 (Build 17763: ).
Testing the performance by creating the first database like this :
CREATE DATABASE DB_BENCH
GO
DECLARE #SQL NVARCHAR(max) = N'';
SELECT #SQL = #SQL + N'ALTER DATABASE DB_BENCH MODIFY FILE (NAME = ''' + name + N''', SIZE = 10 GB, FILEGROWTH = 64 MB);'
FROM DB_BENCH.sys.database_files;
SET #SQL = #SQL + N'ALTER DATABASE DB_BENCH SET RECOVERY SIMPLE;'
EXEC (#SQL);
GO
And the objects in the database like this :
USE DB_BENCH
GO
SET NOCOUNT ON;
GO
CREATE TABLE T_TIME_INTERVAL_TIV
(TIV_ID INT NOT NULL IDENTITY PRIMARY KEY,
TIV_GROUP INT,
TIV_DEBUT DATETIME2(0),
TIV_FIN DATETIME2(0))
GO
TRUNCATE TABLE T_TIME_INTERVAL_TIV;
GO
BULK INSERT T_TIME_INTERVAL_TIV
FROM "C:\DATA_SQL\intervals.txt"
WITH (KEEPIDENTITY ,
FIELDTERMINATOR = '\t',
ROWTERMINATOR = '\n');
GO
CREATE VIEW V
AS
SELECT TIV_GROUP AS id, TIV_DEBUT AS intime, TIV_FIN AS outtime
FROM T_TIME_INTERVAL_TIV
GO
The intervals.txt datafile contains 1 million lines.
You can have it at :
https://1drv.ms/t/s!AqvZfiQYoNpBiCD65D4zaRbch5s-?e=UicEYu
The query that produce the bug :
WITH T1 As
(SELECT id, intime
FROM #T
UNION ALL
SELECT id, outtime FROM #T),
T2 As
(SELECT ROW_NUMBER() OVER(PARTITION BY id ORDER BY intime) NN, id, intime
FROM T1 T1_1),
T3 As
(SELECT T2_1.NN - ROW_NUMBER() OVER(PARTITION BY T2_1.id ORDER BY T2_1.intime,T2_2.intime) NN1,
T2_1.id, T2_1.intime intime, T2_2.intime outtime
FROM T2 T2_1
INNER JOIN T2 T2_2
ON T2_1.id=T2_2.id
And T2_1.NN=T2_2.NN-1
WHERE EXISTS (SELECT *
FROM V S
WHERE S.id=T2_1.id
AND (S.intime < T2_2.intime AND S.outtime>T2_1.intime))
OR T2_1.intime = T2_2.intime)
SELECT id, MIN(intime) intime, MAX(outtime) outtime
FROM T3
GROUP BY id, NN1
ORDER BY id, intime, outtime;
We tested this query on 2 different servers... with the same SQL Server installation.
The result is always :
Msg 601, Level 12, State 1, Line ...
Could not continue scan with NOLOCK due to data movement.
With an installation of :
SQL Server 2019 (RTM) - 15.0.2000.5 (X64) Sep 24 2019 13:48:23 Developer Edition (64-bit) on Windows Server 2019 Standard 10.0 (Build 17763: ) (Hypervisor)
There is no problem...
We tested the databases with DBCC CHECKDB () WITH DATA_PURITY. No errors.
Can you reproduce with your different editions/patches (CU) and give me your results for which are alright or not ?
If some of you have already the bug I will add an entry in SQL Azure feedback...
Thanks
After many investigation, we found that it is really a SQL Server bug.
The bug disappear when we execute a :
UPDATE STATISTICS T_TIME_INTERVAL_TIV WITH FULLSCAN;
Or when whe "hint" the query with OPTION (MAXDOP 1)
Sometime a stack dump appear (not Always) showing this type of messages :
A time-out occurred while waiting for buffer latch -- type 4, bp 0000029BA883BDC0, page 9:407, stat 0x10b, database id: 2, allocation unit Id: 422212465393664/140737488683008, task 0x0000029B86723848 : 14, waittime 300 seconds, flags 0x1a, owning task 0x0000029B86713848. Not continuing to wait.
Which is the tempdb. A Stack Dump is systematically recorded on file.
We will call the MS hotline as soon as possible.
Thanks to all of you.

SQL Server \ CONTAINS FORMSOF INFLECTIONAL Phrase \ Not Working as Expected

I am trying to use the contains operator with FORMOF INFLECTIONAL, but I'm not getting what I think is the expected result.
Here is the query. This query is not returning the record Id 1.
SELECT *
FROM Message
WHERE CONTAINS(*,'FORMSOF(INFLECTIONAL,"01 Hello this is")')
Database objects to reproduce my scenario.
CREATE DATABASE HelpSo
GO
USE HelpSo
GO
CREATE TABLE Message
(
Id INT NOT NULL IDENTITY(1,1),
Text NVARCHAR(MAX)
CONSTRAINT PK_Message PRIMARY KEY (Id)
);
GO
CREATE FULLTEXT CATALOG FtcHelpSo AS DEFAULT
GO
CREATE FULLTEXT INDEX ON Message(Text Language 1033 Statistical_Semantics ) KEY INDEX PK_Message with change_tracking auto
GO
INSERT INTO Message (Text) VALUES ('01 Hello this is a test 20180522.');
INSERT INTO Message (Text) VALUES ('02 Hello this is a test 20180522.');
GO
SELECT * FROM Message;
SELECT *
FROM Message
WHERE FREETEXT(*,'01 Hello this is a test 20180522.') --Returns 2 records. Expected.
SELECT *
FROM Message
WHERE CONTAINS(*,'"01 Hello this is a test 20180522."') --Return 1 record. Expected.
SELECT *
FROM Message
WHERE CONTAINS(*,'FORMSOF(INFLECTIONAL,"01 Hello this")') --Return 1 record. Expected.
-- Here is my problem
SELECT *
FROM Message
WHERE CONTAINS(*,'FORMSOF(INFLECTIONAL,"01 Hello this is")') --Not Expected Result, I think that should return record Id 1.
What I am missing? Why the last query is not returning the record Id 1?
I tried to troubleshotting this issue with the following statements, but I was not able to figure out why i'm getting this result.
SELECT * FROM sys.dm_fts_parser ('FORMSOF(INFLECTIONAL,"01 Hello this is")', 1033, 0, 0)
SELECT *
FROM sys.dm_fts_index_keywords_by_document (DB_ID('HelpSo'), OBJECT_ID('Message'))
WHERE document_id = 1
There is any other tool in the SQL Server that help us solve, or understand better, this kind of issue?
SQL Server Version
SELECT ##VERSION
Microsoft SQL Server 2016 (SP1) (KB3182545) - 13.0.4001.0 (X64) Oct 28 2016 18:17:30 Copyright (c) Microsoft Corporation Developer Edition (64-bit) on Windows 10 Pro 6.3 <X64> (Build 17134: ) (Hypervisor)
I was able to work around this issue by disabling the STOPLIST
ALTER FULLTEXT INDEX ON MESSAGE SET STOPLIST = OFF;
Now I am getting the expected result, in both queries CONTAINS without FORMSOF INFLECTIONAL and CONTAINS FORMSOF INFLECTIONAL.
SELECT *
FROM Message
WHERE CONTAINS(*,'"01 Hello this is a test 20180522."') --Return 1 record. Expected.
SELECT *
FROM Message
WHERE CONTAINS(*,'FORMSOF(INFLECTIONAL,"01 Hello this is")') --Expected Result.
If I change the stop to SYSTEM, the unexpected result is back.
ALTER FULLTEXT INDEX ON MESSAGE SET STOPLIST = SYSTEM;
But I still not understanding why this scenario happened, and what is the proper way to troubleshooting this scenario and connect the dots between the query result and the dm_fts_parser result.
References: Answer - MSDN SQL Server Forum - A problem with using full text search with wildcard query

SQL Server LIMIT 1 and LIMIT 1,1 syntax error

Interestingly enough I found no post for this specific, but basic issue.
Goal: update the latest budgetid record docstatus = 0. Then I want to update the next-to-last budgetid record docstatus = 1. I am trying this within PHP but also testing in my SQL Server SEM and it is failing there, too.
My SQL Server statement:
select
budgetid, docstatus, datechanged
from
ccy_budget
where
activityid = 11111
order by
datechanged desc
limit 1,1;
Error that occurs in SEM is:
Incorrect syntax near 'limit'.
Yet in w3schools this [sample] sql works just fine:
SELECT *
FROM Customers
ORDER BY postalcode DESC
LIMIT 1,1;
Seems so simple, surely I am missing something fundamental.
Microsoft SQL Server 2008 R2 (RTM) - 10.50.1600.1 (X64)
Apr 2 2010 15:48:46
Copyright (c) Microsoft Corporation
Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: ) (Hypervisor)
Equivalent syntax in SQL Server would be
select *
from table
order by somerow desc
offset 1 rows fetch next 1 rows only;
But the above is available from SQL Server 2012 on, so for your version, you have to some thing like below
;with cte
as
(
select *,row_number() over (order by postalcode desc) as rn
from table
)
select * from cte where rn=2

isql DECLARE statement to psql

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?

Resources