Could someone tell me how to read a file's contents into an MS SQL variable using T-SQL?
DECLARE #FileContents VARCHAR(MAX)
SELECT #FileContents=BulkColumn
FROM OPENROWSET(BULK'PathToYourFile.sql',SINGLE_BLOB) x; -- BINARY
--FROM OPENROWSET(BULK'PathToYourFile.sql',SINGLE_CLOB) x; -- CHAR
The SQL Server service account needs to have permissions to read the file obviously.
Make use of SQLCMD to execute the .sql (either from command prompt or within SSMS). If you want to use it within SSMS then first turn the SQLCMD mode (Query >> SQLCMD Mode)
Check out http://msdn.microsoft.com/en-us/library/ms174187.aspx
:r yourFilename
something like:
:r d:\scripts\sample.sql
Related
I developped the following T-SQL script with a bit of SQLCMD to call separate stored procedure script for their creations. The stored procedures are located in a child Store Procedure\ folder (I want to keep the space).
They are probably better ways to perform it, but I wan to a unique script (but using files) which creates the database, the tables, the stored procedures and so on.
I detail neither the the database, nor the table scripting.
/* Create database (I still have some issues with dropping it (existing connections) */
*/ Create tables with constraints... */
-- Is it possible to declare a relative path (here MY_PARENT_PATH is replaced by "c:\...")
:setvar STORE_PROCEUDRE_PATH "[MY_PARENT_PATH]\Stored Procedures"
-- Calls CRUD stored procedures from separate scripts via SQLCMD - is it possible to batch it with all spXXX_XXXX.sql files included in the sub-folder?
:r $(STORE_PROCEUDRE_PATH)\spFields_Create.sql
:r $(STORE_PROCEUDRE_PATH)\spFields_Read.sql
:r $(STORE_PROCEUDRE_PATH)\spFields_Update.sql
:r $(STORE_PROCEUDRE_PATH)\spFields_Delete.sql
-- Idem for other table, such as Features, Values, etc.
Is it possible to loop all files spXXX_XXXX.sql files within the Store Procedure\ folder and execute the :r $(STORE_PROCEUDRE_PATH)\spXXX_XXXX.sql scripts?
I came accross several articles which show example using a FOR construct, but I got confused.
Thanks for any insights :-)
yes there is a way ,
SQLCMD is not able to loop through files but you can use Windows Batch Scripting to accomplish that.
here is a good blog about how to do it :
SQLCMD and Batch File magic
so basically you need to make a .bat file ex: CRUDE.bat and edit and paste below code in it and save it ,
##echo off
cd "[MY_PARENT_PATH]\Stored Procedures"
FOR %%A IN (*.SQL) DO ( sqlcmd -S [SERVERNAME] -d [DATABASE] -U [][username -P password] -i "%%A")
you need to replace these values with your values :
MY_PARENT_PATH : Your path or Directory where your suborder is.
SERVERNAME : Your Database Server Name.
DATABASE1 : Your Database name.
Username : Your SQL Username.
Password : Your SQL Password.
now you can run the batch file and it does the magic.
also here you can find out more about SQLCMD utility
I would like to capture the output of an sqlcmd !! (operating system command) call into a variable that I can use in an insert statement. Or, just read the contents of a file into a variable.
The general idea is something like this:
:SETVAR version !! "type version.txt"
insert into dbo.DeployVersion ([Version],[Date],[User]) values ('$(version)',getdate(),'$(SQLCMDUSER)')
But it doesn't seem that I can chain SQLCMD calls in that way. Any ideas?
type version.txt just prints the content of version.txt file to the console, like cat in linux.
The best I could find was this approach, which seemed really silly.
:setvar quot "'"
declare #versionString nvarchar(300)
set #versionString =
$(quot)
:r .\version.txt
$(quot)
insert into dbo.DeployVersion ([Version],[Date],[User]) values ('$(version)',getdate(),'xyz')
This works in purely SQLCMD and is an answer to the original question.
However, this is being used in an sqlpackage deploy and I don't see a way to externally reference a version.txt file from outside of the dacpac. So instead I added a variable to the dacpac project and I specify that value on the commandline using sqlpackage ... /Variables:Version=%someValueReadFromBatFile%
I have two test Machines. i don't know if this is possible but here is what im trying to do
Machine1: has DBServer setup
where i am currently logged in
where the file C:\test_IDNumber1.txt is located
where i use SSMS. i connect to Machine2\SQLServer
Machine2: has DBServer setup
where the dbserver for DBTest is located
DBTest is where the Filename records are stored
First i need to do some select script from DBTest to get the IDNumber for the Filename
SELECT FileName FROM tblFiles where...... (results to "IDNumber1")
Then i'll check the existence of the file with the same IDNumber (e.g: "C:\test_IDNumber1.txt") using this script
EXEC xp_fileexist 'C:\test_IDNumber1.txt', #exists OUTPUT
If the file exists, i need to delete the record from DBtest on Machine2 and the file from Machine1
DELETE FROM tblFiles where Filename = 'IDNumber1'
EXEC master.dbo.xp_cmdshell 'del ''C:\test_IDNumber1.txt'''
but the result for existence is always 0 because it is checking the C drive of Machine2 where the DBTest is located.
Is there a way to use a select script from a db from Machine2 and check the existence of a file from Machine1?
thank you very much
Several possible solutions can exist. One of the least expensive is:
Make file storage on Machine1 shared, visible to Machine2 and mapped there as network drive (e.g. Z:) with read+delete permissions.
Machine1: C:\Shared\ (mapping)→ Machine2: Z:\
Then you can use SQL commands similar to what you already show in steps 4 and 5 in order to test the existence of Z:\test_IDNumber1.txt and delete the file.
I have a stored procedure, in wWhich I m passing the script file (.sql file) as a parameter.
I want to know how .sql file gets executed through command (not command prompt).
exec my_sp VersionNumber, SqlDeltaScript.sql (it is a file)
I want my stored procedure to execute SqlDeltaScript.sql
Can anyone please help regarding this ...
Thanks in advance ...
This does not sound like an ideal situation, but if you have to do this then you could use xp_cmdshell to run the sqlcmd utility to run your script file.
The xp_cmdshell SP must be enabled in order ot use it - see Enable 'xp_cmdshell' SQL Server.
I have a stored procedure in Sybase that uses reorg rebuild statement in a loop for all the tables in my database. What I want to do is to suppress the reorg rebuild sysmessages for tables that succedeed the procedure and only to print the tables that were locked etc...thus the problematic ones....The thing is that I did not succeed to find out anything to use in manual or in any workshops...dow you have any idea?
Thanks in advance !!!!!
If you are running the SQL with isql at a command prompt, you can always capture the output in a text file and filter it out with other tools.
Create a script to run the SQL in isql and then use a script that calls a text processing tool (awk,sed,...) to only find the lines of interest.
Here is an example from a windows batch file with a regex that removes lines that start with a space (i.e. Rows Effected messages)
isql -SDBDEV1 -DMyDbName -U%DBLOG% -P%DBPWD% -iLoadBatchStats.sql -o%TEMP%\LoadBatchStats.log
type %TEMP%\LoadBatchStats.log | gawk "/^[ ]/{print $0}" >>%TEMP%\LoadBatchSummary.log