Add a line break in sqlcmd output - sql-server

I am working with SQL Server 2019 on Windows. I have a SQL script (.sql file) which I run from the command prompt using sqlcmd.
This is the script:
use master
go
select '$(SQLCMDWORKSTATION)' 'SQLCMDWORKSTATION';
When I run it I get the output:
Changed database context to 'master'.
SQLCMDWORKSTATION
-----------------
HP-ABC-DE-01
In the output I want to put an empty line after "Changed database context to 'master'". How can I do that?

Add a PRINT ''; just after the GO statement.

Related

Using UDF's in Excel SQL Server DB query [duplicate]

How can I execute the following SQL inside a single command (single execution) through ADO.NET?
ALTER TABLE [MyTable]
ADD NewCol INT
GO
UPDATE [MyTable]
SET [NewCol] = 1
The batch separator GO is not supported, and without it the second statement fails.
Are there any solutions to this other than using multiple command executions?
The GO keyword is not T-SQL, but a SQL Server Management Studio artifact that allows you to separate the execution of a script file in multiple batches.I.e. when you run a T-SQL script file in SSMS, the statements are run in batches separated by the GO keyword. More details can be found here: https://msdn.microsoft.com/en-us/library/ms188037.aspx
If you read that, you'll see that sqlcmd and osql do also support GO.
SQL Server doesn't understand the GO keyword. So if you need an equivalent, you need to separate and run the batches individually on your own.
Remove the GO:
String sql = "ALTER TABLE [MyTable] ADD NewCol INT;";
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
sql = "UPDATE [MyTable] SET [NewCol] = 1";
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
It seems that you can use the Server class for that. Here is an article:
C#: Executing batch T-SQL Scripts containing GO statements
In SSMS (SQL Server Management System), you can run GO after any query, but there's a catch. You can't have the semicolon and the GO on the same line. Go figure.
This works:
SELECT 'This Works';
GO
This works too:
SELECT 'This Too'
;
GO
But this doesn't:
SELECT 'This Doesn''t Work'
;GO
This can also happen when your batch separator has been changed in your settings. In SSMS click on Tools --> Options and go to Query Execution/SQL Server/General to check that batch separator.
I've just had this fail with a script that didn't have CR LF line endings. Closing and reopening the script seems to prompt a fix. Just another thing to check for!
Came across this trying to determine why my query was not working in SSRS. You don't use GO in SSRS, instead use semicolons between your different statements.
I placed a semicolon ; after the GO, which was the cause of my error.
You will also get this error if you have used IF statements and closed them incorrectly.
Remember that you must use BEGIN/END if your IF statement is longer than one line.
This works:
IF ##ROWCOUNT = 0
PRINT 'Row count is zero.'
But if you have two lines, it should look like this:
IF ##ROWCOUNT = 0
BEGIN
PRINT 'Row count is zero.'
PRINT 'You should probably do something about that.'
END
I got this error message when I placed the 'GO' keyword after a sql query in the same line, like this:
insert into fruits (Name) values ('Apple'); GO
Writing this in two separate lines run. Maybe this will help someone...
I first tried to remove GO statements by pattern matching on (?:\s|\r?\n)+GO(?:\s|\r?\n)+ regex but found more issues with our SQL scripts that were not compatible for SQL Command executions.
However, thanks to #tim-schmelter answer, I ended up using Microsoft.SqlServer.SqlManagementObjects package.
string sqlText;
string connectionString = #"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=FOO;Integrated Security=True;";
var sqlConnection = new System.Data.SqlClient.SqlConnection(connectionString);
var serverConnection = new Microsoft.SqlServer.Management.Common.ServerConnection(sqlConnection);
var server = new Microsoft.SqlServer.Management.Smo.Server(serverConnection);
int result = server.ConnectionContext.ExecuteNonQuery(sqlText);

sqlcmd scripting variables understanding problem

try to run sqlcmd from powershell with some variables.
But get error.
Simple test. I know that this select is really simple but it is sufficient to show the problem.
this is the content of my sql file:
USE [master]
select name from sys.databases where NAME = $(db)
GO
now i run this:
sqlcmd -S testserver -v db="Test" -i \mssql_duplicate\testvariable.sql
i get following message:
Meldung "207", Ebene "16", Status "1", Server "testserver", Zeile 2
"Ungültiger Spaltenname "Test"."
So my question: Why the sqlcmd do this conversion?
When i put he name in the sql script it runs fine:
USE [master]
select name from sys.databases where NAME = "TEST"
GO
sqlcmd -S testserver -i \mssql_duplicate\testvariable.sql
Thanks for your help!
SQLCMD variables can substitute anything, in particular databases' and objects' names. In your example, however, it is used as an ordinary parameter, which is supposed to be of nvarchar(128) data type. So your code should look like this:
USE [master];
select name from sys.databases where NAME = N'$(db)';
GO
Without single quotes, SQL Server interprets your variable as an object name, hence the error.

Not getting ouput after successful execution of the SQL scripts through powershell

I have to automate one process to get rid of daily effort reduction in our organization. We need to execute multiple scripts on different SQL Server instances and each script contains database name as well.
So initially our client put all the scripts on a particular location and I need to execute each of the scripts and then move the script file to different folder.
After a script got an error, it logged the error and one file has been generated.
After successful execution I need to generate one log file where all the successful results script wise also getting generated. Like when we execute one script in SSMS, after executing the script it generates a message like "1 row affected".
How can I do that?
invoke-sqlcmd -inputfile "E:\test.sql" -serverinstance ".\Your_Instance_Name" -database "user" | out-File -filepath "E:\result.txt"
The "1 row(s) affected" message is generated automatically, unless set nocount is specified.
A client application, such as Invoke-SqlCmd, SSMS and sqlcmd, can do whatever with the row count number. SSMS and sqlcmd print it per default, Invoke-SqlCmd doesn't seem to do that. This is not a bug, though it's certainly a bit surprising.
The simple approach is to issue an explicit select for ##ROWCOUNT. Like so,
insert mydb.schema.table(column1, column2....) values(...); select ##rowcount;
Or, use sqlcmd.exe instead.

SSMS query - script won't run if database does not exist

I'm trying to do something like:
"If it exists, use it. If not, create it."
"If it exists, delete it. If not, create it."
One place it's definitely choking is the use it command - because if it DOES NOT EXIST - it chokes on the use command EVEN THOUGH that command will not run.
Here's more explanation:
I have a SQL Server script where I create a database and then I use the database.
The script will not run
because the use database command is invalid
because the database does not exist
but it will exist after the first command executes
but it doesn't matter because it doesn't exist NOW so the script will not run.
How do I put code in there that tries to use a database that might not exist?
How do I put code in there that will cause an error if run directly but WILL NOT RUN unless conditions are appropriate.
Please see the attached images.
Here's the code so you don't have to type it...
-- SQL SERVER: We can't run this script because CFPT does not exist.
-- ME: But it WILL exist after the first command runs
-- SQL SERVER: That does not matter - at THIS point in the code... it does not exist... tough luck
-- CREATE THE DATABASE
create database CFPT
-- USE THE DATABASE
USE CFPT
use master
drop database CFPT
Second code snippet:
-- SQL SERVER: We can't run this script because CFPT does not exist.
select db_id('CFPT') -- this just lets us see what the IF statement is going to have to deal with
IF db_id('CFPT') is null
begin
print 'DESIRED DB DOES NOT EXIST'
return
end
else
begin
use CFPT -- this line of code makes the whole script just not run.
end;
-- doesn't want to work - chokes on the use databasename (when the database does not exist)
(EDIT 1 start ////////////////////////////////////////////////////////////////////////////////////)
A third image was added with this edit - The SECOND image shows that the if/then/else statement will not work. The 3rd image shows that the database CFPT is not in the database list (left side of image) and the select statement was run (top highlighed code) and the results of that select (bottom red circle)
How do I get the if/then/else statement to work? (Because the THEN will not run if the conditions are not favorable shall-we-say)
(for some reason the red wavy lines are not showing up - they should be but they aren't - hmmm)
(EDIT 1 end ////////////////////////////////////////////////////////////////////////////////////)
(EDIT 2 start ////////////////////////////////////////////////////////////////////////////////////)
In relation to this question - trying to segregate commands that would normally fail but will not be attempted to be executed unless conditions are just right..... (see 4th image below) I'm segregating some commands with an IF statement (IF 1=2) but SQL Server is going into that IF statement even though the condition is false. Why is that?
(EDIT 2 end ////////////////////////////////////////////////////////////////////////////////////)
Try this ...
-- CREATE THE DATABASE
create database CFPT
GO
-- USE THE DATABASE
USE CFPT
use master
drop database CFPT
The GO command is a batch terminator, it separates the command to create the database from the command to use it.
See https://msdn.microsoft.com/en-us/library/ms188037.aspx
and
What is the use of GO in SQL Server Management Studio & Transact SQL?

Sql Server insert command adding "Â" to an NVarChar column

I have a sql command as follows:
INSERT [dbo].[Currency] ([CurrencyID], [Description], [Symbol])
VALUES (N'7418fe34-1abc-4189-b5f1-e638a34af1a1', N'GBP', N'£')
When I run this against the database, it inputs the last column as '£' rather than '£'. I have come across this before but can't for the life of me remember how to fix it!
Any ideas?
Thanks.
UPDATE
Funnilty enough, if I copy and paste that line from my sql file into sql man stud, then it inserts fine. So I think there is something wrong with my sql file, and a possible character in it that I cant see?
UPDATE
The sql script has the following to insert the euro symbol:
INSERT [dbo].[Currency] ([CurrencyID], [Description], [Symbol])
VALUES (N'c60b1e0c-289a-4a0a-8c7d-30a490cbb7a8', N'EUR', N'€')
And it outputs "€" in the database for the last column
UPDATE
Ok, I have now copy and pasted my full sql file into Sql Server and run it, and it now inserts everything fine. So why does this issue arise only when I run my ".sql" file?
UPDATE
Another update! If I view the ".sql" file in Visual Studio it looks fine, however if I open it within notepad, the bogus characters appear!
(From the comments)
The file is saved as UTF-8, but sqlcmd is reading it using the wrong code page. Adding -f 65001 to the options tells sqlcmd to read it as an UTF-8 file.

Resources