Default encoding in SQL Server Management Studio - sql-server

I have recently had SSMS 2008 re-installed on my laptop
When I click "New Query..", I am now prompted to select the encoding for the file, something I was never asked to do before
I have associated sql againt "SQL Query Editor with Encoding" in the Text Editor section of the Option and restarted SSMS
What can I do to associate with an encoding as I don't want to select everytime I do a new query or open an existing sql file

As per the workaround posted by Fakher Halim on Microsoft Azure Feedback Forums.
I had the same issue. Git wouldn't show any differences in history
(besides "Binary files a/x.sql and b/x.sql differ). So I clicked
Tools=>Options=>Environments=>International Settings. Changed the
Language from "English" to "Same as Microsoft Windows". Now GIT DIFF
works perfectly well -- reports version difference normally!

Based on the advice given elsewhere (https://feedback.azure.com/forums/908035-sql-server/suggestions/32892454-need-a-way-to-set-the-default-encoding-for-query-f) I've hacked up a "command script" to attempt to "change the default encoding" to UTF-8 with a BOM. The script works by writing a UTF-8 w/ BOM template to a SQLFile.sql file within the Program Files tree of SQL Server. It has worked once on my machine, but that doesn't mean that it's bugfree or 100% safe. USE AT OWN RISK!
According to "Microsoft's" response in that thread:
The default for how files are saved is determined by the way the main template file SQLFile.sql located at C:\Program Files\Microsoft SQL Server\90\Tools\Binn\VSShell\Common7\IDE\sqlworkbenchprojectitems\Sql. If you save this file using ANSI encoding, then subsequent new query sessions will use this encoding.
Note that on my machine I found the template at a different path so I wrote the script to find any file matching that name under either Program Files. It seems like a silly enough name that false collisions should be rare.
If passed no arguments (or any arguments other than what it expects) then it should do a dry-run. Make sure to run it without administrative privileges first. It will at least find any applicable files and you can decide then if you want to proceed with the script or modify the files yourself.
To run the script for real then pass a first argument of "force". This is the dangerous part. Heed caution. To run the script to completion without pausing for user input then pass a second argument of "dontpause" (this can be passed with an empty first argument to skip pausing during a dry-run).
I choose UTF-8 because it's 7-bit ASCII compatible, it supports the vast majority of languages and characters you'll ever care to script, it stores Western text and source code very efficiently, and it's source control/text patch friendly. The template at the bottom of the script contains a byte-order mark (BOM) to signal editors that it is not ISO-8859-1 or some other incompatible default 8-bit encoding. Be sure it isn't lost when you copy/paste. Save the actual batch script as ASCII (or compatible; without a BOM!). The command processor chokes on a UTF-8 BOM.
#echo off
setlocal ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION || exit /b 1
if "x%1" == "xforce" (
echo Force enable. Danger Will Robinson! This means that I'm going to
echo attempt to move files and write a new file to replace them. This
echo is potentially destructive if there are any bugs in this script.
echo In particular, if there are any unrelated files with the name
echo sqlfile.sql under your Program Files directories then they'll be
echo corrupted.
echo.
echo This script is going to require elevated privileges to write to
echo Program Files. Execute the Command Prompt application as an
echo administrator to proceed ^(should be harmless to try without
echo elevation first^).
echo.
echo I RECOMMEND YOU _DO NOT_ RUN THIS SCRIPT FROM WINDOWS EXPLORER
echo BECAUSE YOU MAY HAVE A HARDER TIME READING THE OUTPUT. Start a
echo Command Prompt and run it there.
echo.
if not "x%2" == "xdontpause" (
echo Now is a good time to Ctrl+C ^(and Y^).
pause
)
) else (
echo Dry-run enabled. Pass a lone argument of "force" to go for real. 1>&2
echo Be careful running the script several times. Your template backup
echo will be overwritten and lost.
)
set paths="C:\Program Files (x86)\SQLFile.sql" "C:\Program Files\SQLFile.sql"
for /f "tokens=*" %%f in ('dir /a /b /s %paths% 2^>NUL') do #(
echo.
echo Found: %%f
if "x%1" == "xforce" (
echo Moving to: %%f.orig
echo.
echo If you ^(or anything else^) has made any changes to your template
echo then you should be able to recover your template from the backup
echo file above ^(not yet, once you continue^) ^(alternatively,
echo recover the template from the source file now^).
if not "x%2" == "xdontpause" (
pause
)
move "%%f" "%%f.orig" || exit /b 1
)
echo.
echo Writing a standard UTF-8 template with byte-order mark ^(BOM^).
echo Feel free to open this file up afterward and manually set the
echo encoding preferred. You can also replace it with your own
echo template text.
if not "x%2" == "xdontpause" (
pause
)
set ok=0
rem Read in myself, look for the __BEGIN__ marker and write
rem subsequent lines to the file.
for /f "tokens=*" %%g in (%~dpf0) do #(
if !ok! == 1 (
if "x%1" == "xforce" (
if "x%%g" == "x." (
echo.
echo.>>"%%f"|| exit /b 1
) else (
echo %%g
echo %%g>>"%%f"|| exit /b 1
)
)
) else (
if "%%g" == "__BEGIN__" (
echo.
echo Found marker. Starting write on next ^(non-empty^) line... 1>&2
echo.
set ok=1
)
)
)
)
exit /b 0
Below is the SQL template. Lines containing only a dot (.) represent
blank lines. Actual blank lines will be lost.
__BEGIN__
BEGIN TRANSACTION;
.
SET XACT_ABORT ON;
.
.
.
ROLLBACK;
--COMMIT;

In SQL Server Management Studio, select Tools/Options then expand "Text Editor" and add the extension "sql" and map it to "SQL Query Editor".
The solution works if you are working with ASCII characters. If the sql contains characters that require explicit encoding (as determined by the SQL editor) then you will must select an encoding. The issue comes into play when creating files in both the SQL editor and other editor (NotePad++), then editing those files in the other editor. NotePad++ saves files without the header and can guess the encoding. The SQL editor on the other hand always requires the encoding header once certain characters are used.

Previous answers have suggested using Tools→Options→Environments→International Settings, but this option is not present in SSMS 17.2.
Instead, you can go to File→Save As..., click the arrow on the "Save" button, and select "Save with Encoding".

I am such an idiot - I changed the association to "SQL Query Editor" and it now all works fine
The "with Encoding" bit should really have tipped me off!

Related

Printing ZPL file using Batch File Issue

We run NetSuite for our shipping software and use Zebra ZP450 printer to print the thermal label.
The software downloads a .zpl file which I have assigned to run with a batch file, script here:
Net use LPT2: \\%ComputerName%\ZebraFedex
Copy %1 LPT2
Net use LPT2: /Delete
I have installed this on probably 20 or more computers without an issue. But the last two will initiate the batch file but not print.
I was able to hit pause on the batch file and here is what I got:
C:\users\noah\downloads\net use LPT2: \(ComputerName)\ZebraFedex
The command completed successfully
C:\Users\Noah\Downloads\Copy LPT2
The system cannot find the file specified. 0 files copied
C:\Users\Noah\Downloads>Net use LPT2: /Delete
I've checked my file association, which seems correct since I see the command prompt flash on the screen. I have no idea here...
Working successfully on another computer
Problem on puzzling computer
Here's my batch to transfer file to my venerable TLP2844:
#ECHO OFF
SETLOCAL
FOR %%a IN (%*) DO (
IF EXIST "%%a" (COPY /b "%%~a" \\%computername%\TLP2844
) ELSE (
IF EXIST "%%a.txt" (
COPY /b "%%~a.txt" \\%computername%\TLP2844
) else (
ECHO Neither "%%a" nor "%%a.txt" appears to EXIST
)
)
)
where I have a printer called TLP2844 installed as a ZDesigner TLP 2844 device on USB003.
The problem, as shown by the graphics I've included in your question (saves running off chasing links) is that the label file C:\users\melan\downloads\UPSSHIPPINGLABEL1700448.zpl is being provided to the batch as %1 (first parameter). On the problem installation, no filename (presumably C:\users\Noah\downloads\UPSSHIPPINGLABEL???????.zpl is being provided to the batch as %1.
Therefore it's not a batch problem, but a problem with Netsuite.
From your .pdf, on page 26 :
To install a thermal printer driver on a Windows PC:
...
5. In the Share Name field, enter the name of the printer. For example, LP 2844.
The printer name cannot contain spaces.
So you're told the printer name cannot contain spaces, but the example printer name contains a space....Excellent! (shows my level of confidence in the product, but not actually directly relevant to the problem) :(
Personally, I'd change your batch file to
Copy %1 \\%ComputerName%\ZebraFedex
Perhaps you'd try that after fixing the problem where Netsuite fails to deliver the filename to the batch. Perhaps it's set up to produce .pdfs on the computer in question (That's a wild guess)
In response to reply:
Please change your batch file (temporarily for test purposes) to this:
Echo File to print : "%1"
Net use LPT2: \\%ComputerName%\ZebraFedex
Copy %1 LPT2
Net use LPT2: /Delete
PAUSE
which will report the filename supplied by Netsuite to the batch file on the console window, then keep the window open at the end of the batch until the open window receives a keystroke.
Please report results for both a "working" and a "buggy" installation.
Change .bat file like below, replacing the printer share name with your own. Happened on one of our critical computers that is also the host for FedEx/UPS.
C:\WINDOWS\system32\net.exe use LPT2: \\%ComputerName%\Zebra_ZP500_Shipping_FedEx1
Copy %1 LPT2
C:\WINDOWS\system32\net.exe use LPT2: /Delete
Thank you Noah Schultz for the Pause suggestion for batch file, and to QWERTY for article on Net command issue
Reference

Windows 10 batch files: Weird behaviour on files that worked in previous versions

So I have the following batch file, which launches a game server for Sauerbraten:
#ECHO OFF
set SAUER_BIN=bin
IF /I "%PROCESSOR_ARCHITECTURE%" == "amd64" (
set SAUER_BIN=bin64
)
IF /I "%PROCESSOR_ARCHITEW6432%" == "amd64" (
set SAUER_BIN=bin64
)
start %SAUER_BIN%\sauerbraten.exe "-q$HOME\My Games\Sauerbraten" -gserver-log.txt -d %*
The batch file comes by default with the game install, and worked fine on Windows 7.
When I run it as admin, I get the following error in a popup window:
Windows cannot find 'bin64\sauerbraten.exe'. Make sure you've typed the name correctly, then try again.
I have verified that the file is there and that the spelling is correct.
In the same directory, there is another batch file to launch the game itself, which is identical except for a couple of launch parameters in the last line. When run, it works fine. I have copy-pasted this file into the other and made the changes visible in case there were invisible characters or anything, but that made no difference.
#ECHO OFF
set SAUER_BIN=bin
IF /I "%PROCESSOR_ARCHITECTURE%" == "amd64" (
set SAUER_BIN=bin64
)
IF /I "%PROCESSOR_ARCHITEW6432%" == "amd64" (
set SAUER_BIN=bin64
)
start %SAUER_BIN%\sauerbraten.exe "-q$HOME\My Games\Sauerbraten" -glog.txt %*
When not running as admin, the server actually seems to launch (as it outputs to the log file and gives an error stating it could not create the server host, which I suspect to be associated with needing to run as admin).
Why am I seeing this behaviour? I can't think of any reasonable explanation.
Depending upon how your executable accepts its arguments, I'd suggest either:
#Echo Off
Set "SAUER_BIN=bin"
If Defined PROCESSOR_ARCHITEW6432 Set "SAUER_BIN=bin64"
If %PROCESSOR_ARCHITECTURE:~-2%==64 Set "SAUER_BIN=bin64"
Start "" "%~dp0%SAUER_BIN%\sauerbraten.exe" -q"$HOME\My Games\Sauerbraten" -g"log.txt" -d"%*"
Or:
#Echo Off
Set "SAUER_BIN=bin"
If Defined PROCESSOR_ARCHITEW6432 Set "SAUER_BIN=bin64"
If %PROCESSOR_ARCHITECTURE:~-2%==64 Set "SAUER_BIN=bin64"
Start "" "%~dp0%SAUER_BIN%\sauerbraten.exe" "-q$HOME\My Games\Sauerbraten" "-glog.txt" "-d%*"
I have no control over your additional arguments, so you'll have to decide whether it should read "%*" or %*.

Is there a work around for ":" (colon) when downloading from ftp using windows

I'm creating a batch script to a get a file based on what option the user chooses. The only problem is, the file in the ftp server has a colon and from what i've researched, windows does not accept ":" colon.
Is it possible to replace that character before downloading?
Below is a sample of my code.
Echo open sample.net>first.dat
Echo user>>first.dat
Echo password>>first.dat
Echo ascii>>first.dat
Echo cd directory>>first.dat
Echo lcd folder>>first.dat
Echo get sample-text-10-16-2017_16:36:00:340033.txt>>first.dat
Echo bye>>first.dat
ftp -v -i -s:first.dat
del first.dat
As you can see also, I get a list first of the file names inside the folder for the user to input the file name. I just wrote a specific file name for the example
I'm still not familiar with the for loops in batch but I think that it is one way of replacing the characters in a file name before downloading
[Untried]
get remotefilename localfilename
is apparently valid, so placing a valid windows filename as a second argument should d/l to the file specified.
[Addendum - also untried]
(after Echo lcd folder>>first.dat)
echo mls remotefilesrequired awindowlistfilename>>first.dat
rem this should log in and create awindowslistfilename
rem containing the remote filelist
ftp -v -i -s:first.dat
del second.dat 2>nul
setlocal enabledelayedexpansion
for /f "delims=" %%a in (awindowslistfilename) do (
set "remote=%%a"
echo get !remote! !remote::=.!>>second.dat
)
endlocal
Echo bye>>second.dat
ftp -v -i -s:second.dat
del first.dat
del second.dat
Since I'm not aware of the return format for mls, I'm assuming that it's a simple file-list, one to a line.
This code first executes the ftp log-on palaver and an mls command, creating awindowslistfile locally.
It then deletes second.dat (the 2>nul suppresses error messages like file not found appearing on stderr)
setlocal enabledelayedexpansion and endlocal bracket a mode where the syntax changes such that !var! may be used to access the run-time value of a variable, whereas %var% always refers to the parse-time value.
The for/f command reads the filename (parenthesised) and assigns each line in turn to the metavariable %%a. The delims= option ensures that the entire line is assigned, ignoring the normal tokenising procedure.
A series of individual get commands is then written to second.dat, with the substitution of : by . in the name.
Finally, add the bye and FTP again.
(I'm not sure whether first.dat will also require a bye and second.bat will need to prelimnary commands, but could be...)
Note that it's batch convention to enclose filenames that may contain separators like Space,; in "quotes". How FTP will feel about that, if necessary, I can only guess.
Naturally, extra lines within the loop
set "remote=!remote:x=y!"
could be used to serially replace character sequences x by y if there are any other problematic characters encountered.

Timestamp Not Returned in Batch

I am trying to run a batch file to update some software if the exe file is timestamped before the most recent version. To do this, I am using a well known for loop.
When I do this:
set file=%AppData%\spark\spark.properties
for %%a in (%file%) do set olddate=%%~ta
echo %olddate%
A timestamp is returned.
When I run it like this:
set spark_exe=%ProgramFiles%\Spark\Spark.exe
for %%a in (%spark_exe%) do set olddate=%%~ta
echo %olddate%
A timestamp is not returned. (Nor for any other files in that folder)
If I run:
set spark_exe=%ProgramFiles%\Spark\Spark.exe
for %%a in (%spark_exe%) do set fqp=%%~fa
echo %fqp%
I get the fully qualified path.
So... I can use SOME expansion variables.. but not others... why?... how?... help?
Thanks :)
I tried the batch code below and it worked:
#echo off
if exist "%ProgramFiles%\Spark\Spark.exe" (
set "spark_exe=%ProgramFiles%\Spark\Spark.exe"
) else if exist "%ProgramFiles(x86)%\Spark\Spark.exe" (
set "spark_exe=%ProgramFiles(x86)%\Spark\Spark.exe"
) else (
echo Error: Could not find Spark.exe
pause
goto :EOF
)
for %%a in ("%spark_exe%") do echo %%~ta
set "spark_exe="
I replaced also %%~ta by %%~fa to get name of file with path instead of last modification date and it worked, too.
Then I used Process Monitor of Sysinternals and logged the file system accesses on Spark.exe.
I could see that cmd.exe makes two IRP_MN_QUERY_DIRECTORY requests of type FileBothDirectoryInformation to check if the file exists and get full name of the file on using in batch file %%~fa.
There are the same two IRP_MN_QUERY_DIRECTORY requests with %%~ta in batch file. But additionally there is also a IRP_MJ_QUERY_INFORMATION request which is different to IRP_MN_QUERY_DIRECTORY as it is done with a file handle.
Is it possible that Spark.exe is currently created by the compiler when the batch file is executed and therefore any access on file is denied for any other application like cmd.exe?
I suggest to use also Process Monitor of Sysinternals and define Path ends with Spark.exe as include filter. Then run your batch file. Look now in Process Monitor if you can see any access denied in the log.

Add/remove keyboard languages through .bat

Some time now that I am using win7, it regularly messes my keyboard languages up, and I have to remotely add 3 keyboard languages, apply, and then remove them. So, I was wondering if there is a way to do it through a .bat file automatically(add 3 specific keyboard languages and then immediately remove them). However, I know almost nothing about .bat commands, so does anyone know if this is possible through a .bat file and if yes, what commands shall I use?
Thank you in advance,
George.
It's possible.
http://blogs.msdn.com/b/shawnste/archive/2007/04/12/configuring-international-settings-from-the-command-line.aspx
http://msdn.microsoft.com/en-us/goglobal/bb964650#eyb
command line example to run the xml to add the keyboard language:
control intl.cpl,, /f:"%CD%\AddKeyboardLanguage.xml"
AddKeyboardLanguage.xml used to add Chinese keyboard language example:
<gs:GlobalizationServices xmlns:gs="urn:longhornGlobalizationUnattend">
<gs:UserList>
<gs:User UserID="Current" CopySettingsToDefaultUserAcct="true" CopySettingsToSystemAcct="true"/></gs:UserList>
<gs:InputPreferences>
<gs:InputLanguageID Action="add" ID="0804:{81D4E9C9-1D3B-41BC-9E6C-4B40BF79E35E}{FA550B04-5AD7-411F-A5AC-CA038EC515D7}"/>
</gs:InputPreferences>
</gs:GlobalizationServices>
RemoveKeyboardLanguage.xml example:
<gs:GlobalizationServices xmlns:gs="urn:longhornGlobalizationUnattend">
<gs:UserList>
<gs:User UserID="Current" CopySettingsToDefaultUserAcct="true" CopySettingsToSystemAcct="true"/></gs:UserList>
<gs:InputPreferences>
<gs:InputLanguageID Action="remove" ID="0804:{81D4E9C9-1D3B-41BC-9E6C-4B40BF79E35E}{FA550B04-5AD7-411F-A5AC-CA038EC515D7}"/>
</gs:InputPreferences>
</gs:GlobalizationServices>
Batch file to add or remove the keyboard language (save as AddRemWindowsChinese.bat):
#echo off
if "%1"=="" echo ERROR: Missing [add]/[remove] parameter & goto :USAGE
if /i %1==add (
echo control intl.cpl,, /f:"%CD%\AddWindowsChinese.xml"
control intl.cpl,, /f:"%CD%\AddWindowsChinese.xml"
IF ERRORLEVEL 1 echo An error occured ! && goto :ERROR
)
if /i %1==remove (
echo %CD%
echo control intl.cpl,, /f:"%CD%\RemoveWindowsChinese.xml"
control intl.cpl,, /f:"%CD%\RemoveWindowsChinese.xml"
IF ERRORLEVEL 1 echo An error occured ! && goto :ERROR
)
GOTO :END
:USAGE
echo.
echo USAGE:
echo AddRemWindowsChinese.bat [add ^| remove]
echo.
pause
goto :END
:ERROR
:END
I also have been experiencing the same problem - en-US is added automatically, and I had to add en-US and then remove it in order to get rid of the layout. Even with the batch file, I found that you cannot just remove it, you have to first add the layout (even if it is showing on the keyboard layout list) to be able to remove it just like when you do it manually.
Hence, the Remove_en-US.xml file first adds the layout and then remove it:
<gs:GlobalizationServices xmlns:gs="urn:longhornGlobalizationUnattend">
<!--User List-->
<gs:UserList>
<gs:User UserID="Current"/>
</gs:UserList>
<!--input preferences-->
<gs:InputPreferences>
<!--add en-US keyboard input-->
<gs:InputLanguageID Action="add" ID="0409:00000409"/>
<!--remove en-US keyboard input-->
<gs:InputLanguageID Action="remove" ID="0409:00000409"/>
</gs:InputPreferences>
</gs:GlobalizationServices>
Remove_en-US.bat:
control intl.cpl,, /f:"%CD%\Add_en-US.xml"
Here, 0409 is the locale ID and 00000409 is the keyboard layout values. For the list of the locale ID:keyboard layout value see https://learn.microsoft.com/en-us/previous-versions/windows/it-pro/windows-8.1-and-8/hh825682(v=win.10).
Using #Ying tips/link...
I made a pt.xml file:
<gs:GlobalizationServices xmlns:gs="urn:longhornGlobalizationUnattend">
<!--User List-->
<gs:UserList>
<gs:User UserID="Current"/>
</gs:UserList>
<!--input preferences-->
<gs:InputPreferences>
<!--add pt-BR keyboard input and set as default-->
<gs:InputLanguageID Action="add" ID="0416:00010416" Default="true"/>
</gs:InputPreferences>
</gs:GlobalizationServices>
and then just create a .bat with this command inside:
control intl.cpl,, /f:"%CD%\pt.xml"
Double click it and it should work instantly!
Keyboard languages are stored in the registry under HKEY_CURRENT_USER\Keyboard Layout You can use REG.EXE in Batch files to add/modify/remove registry keys. REG.EXE doesn't support remotely changing HKEY_CURRENT_USER registry keys so the file would have to be ran from the computer in question. We probably don't have to do that though. This is what I would do. When your computer is working as it should, Goto a CMD prompt by clicking the start button and typing CMD into the run box. From the CMD prompt, type:
REG QUERY "HKCU\Keyboard Layout" /s
This will show you what the registry keys should look like when all is well. Now take a snapshot of that and store it in a file by typing:
REG EXPORT "HKCU\Keyboard Layout" KeyboardLayout.reg
This will create the KeyboardLayout.reg file in whatever directory your CMD prompt says. I'm not sure why you would have to add 3 specific languages and then remove them to get back to working order but I have a feeling that just setting the registry back to the way it was when it worked would fix the problem. The next time it happens, remotely browse to the location of the KeyboardLayout.reg file and double click it. It will tell you the key has been updated and to click ok. See if that fixes it. If it doesn't, reboot that computer and see if it does then. If it still doesn't work, post back a comment and I'll tell you what I'd do next.
there is a powershell method as well. Here is simple batch to remove en-US and de-DE layouts
#echo off
for %%q in (en-US de-DE) do ^
powershell -c "$ll=Get-WinUserLanguageList; $ll.add('%%q'); Set-WinUserLanguageList $ll -force;" & ^
powershell -c "$ll=Get-WinUserLanguageList; $ll.remove(($ll |? LanguageTag -like '%%q')); Set-WinUserLanguageList $ll -force;"
first we have to add them, then remove. works fine for me.

Resources