How do I use sql scripts to retrieve these guids - sql-server

In SQL Server filestream storage, I find these guids in my Windows SQL Server folder. I don't know if they can be obtained by using SQL scripts.
Where are these guids coming from ?

You can. There are multiple ways of accomplishing this, from simple, specific CLR applications to the undocumented stored procedures Microsoft has included.
DISCLAIMER: The following procs are limited to permissions that the
account SQL Server Agent runs under.
xp_dirtree - undocumented
Returns a tabular result set from the directory path. Second parameter sets the depth of subdirectories to traverse (0 means return all subdirectories). Third parameter is BIT that decides whether to include files in result set.
EXEC master.sys.xp_dirtree '<directory_path>', 0, 1
xp_fileexist -undocumented
Great for checking single locations pre-steps before inserting files in a script.
EXEC master.sys.xp_fileexist 'C:\FilesCompare_SQL Files\FilesCompare.txt'

Related

Azure SQL - How to skip USE statement in Azure SQL while having it work in SQL Server

I am trying to update an old script in a production installer so that it can work with both Azure SQL and SQL.
The problem is that our script is calling USE to switch the database. On prem we are creating the database, in Azure it will already be created for us... so we are detecting its existence and moving on. However that is where we are then calling USE to switch, for on prem.
I was hoping I could skip it like this in Azure
IF NOT SERVERPROPERTY('edition') = 'SQL Azure'
USE MYDB
I am still getting the "USE statement is not supported to switch between databases."
The hack is to put this into a string and run it with: EXEC sp_executesql
This works for most things, but I don't think it works with the USE statement.
Is there any way I can let the Azure SQL parser skip this section, as it will never be executed?
I am open to SQL based workarounds... but I am trying to avoid rearchitecting the installer.
USE statement is not supported to switch between databases
On Azure SQL Database this error only occurs when you try to 'USE' a different database.
In Azure SQL Database, the database parameter can only refer to the
current database. If a database other than the current database is
provided, the USE statement does not switch between databases, and
error code 40508 is returned.
USE (Transact-SQL)
Similarly three-part names referencing the current database are allowed.

Create a stored procedure that generates SQL Server Agent jobs

Curious if this is feasible. I am currently in the process of building a number of SQL Server agent jobs. These jobs are just SFTP jobs that pass files between the servers of 2 different clients, making a pit-stop at my local server for some pre and post processing. Yes, this setup is from one standpoint unnecessarily complicated, but it is necessary from a security standpoint. All of these jobs have identical structure:
SFTP a file from the client1server to the local server.
Run an executable on the file
SFTP the processed file to client2server.
Wait a predetermined amount of time so that client2 can perform their query on the input.
SFTP the response file from client2server to the local server.
Run a second executable on the file.
SFTP the processed response file back to client1server.
Pretty straight forward.
There are only a handful of values that change between each job:
- Input/output file path on client1server
- Input/output file path on client2server
- Directory on local server
These jobs are not complicated, so If necessary I can just create them all by hand. It seems like an unnecessary amount of work though. I had the thought that maybe I could create a stored procedure that would generate the SQL script that creates the job, and that stored procedure could simple accept the variables that change from job to job. Is this feasible?
Broadly, heres what I'm thinking:
CREATE PROCEDURE create_ftp_interface_job
#client1input_fp nvarchar(100),
#client1output_fp nvarchar(100),
#client2input_fp nvarchar(100),
#client2output_fp nvarchar(100),
etc...
AS
<SQL Script for creating SQL Server Agent jobs, with parameters inserted>
GO
I've tried an early version of this, and I seem to be having trouble referencing the variables I declare in the stored procedure definition inside of the SSA job script. I came here to ask if what I'm attempting is feasible, and I just have a run of the mill reference error, or if what I'm doing is not allowed.
You can use msdb.dbo.sp_add_job, msdb.dbo.sp_add_jobstep, msdb.dbo.sp_update_job, msdb.dbo.sp_add_jobschedule and msdb.dbo.sp_add_jobserver to create and manage SQL Agent Jobs programatically.
In fact there are even more stored procedures here which relate to managing SQL Agent Jobs.

SQL Server running a filecheck on a different server

I'm really bad at SQL and couldn't find anything near what I really need. I'm trying to create a Stored Procedure that should run each night to check if records in my database have an equivalent file on a server with all our data.
Example: Record with a mp4 has: [Spotnumber] -> 0000001. Then my procedure should check (not locally) if the file exists on the other server with this number.
Also the place where it should look could be fore exemple (not locally) C:/Spots. And in this directory there'll be subdirectories like: 2013, 2012, 2011. It should check in each directory if it doesn't exists.
For this I was thinking to make something like this: Single check. But this one searches locally and already has the url in a table-field. This won't be possible for mine.
So my question is: Is it even possible to do this with just a SQL procedure? If yes how should I make it check all the files on another server (what path should I use?) + How can I make it check for each record in each subdirectory?
I would suggest another approach.
Instead of using Sql server to check if the file exists then update the db.
Why don't you use a powershell script checking if a file exist, then in this powershell script update the database. With a little search on google you can find all functions on microsoft blogs explaining how to check if a file exists and update file.
Another solution, you could create an assembly in your database with a .net language and work with that.
Last possibility, i think it can be possible too with SSRS.
If you really need to do that with tsql, you should allow xcmd command on your server, then use xcmd... but it means every body could use xcmd. It's not designed too and not suggested :)

SQL Server Copy Database Issue

I'm running the copy database wizard on a 2008 R2 instance of SQL Server.
The database I want to copy is a SQL 2000 database.
I'm copy that database to another SQL SErver 2008 R2.
The wizard uses SQL authentication for both servers, and both are sysadmins.
When I run it, I get the following error (FYI I have tried both copying the logins and leaving them out):
Event Name: OnError
Message: ERROR : errorCode=-1073548784 description=Executing the query "sys.sp_addrolemember #rolename = N'RandomRoleName..." failed with the following error: "The role 'RandomRoleName' does not exist in the current database.". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.
helpFile= helpContext=0 idofInterfaceWithError={C81DFC5A-3B22-4DA3-BD3B-10BF861A7F9C}
StackTrace: at Microsoft.SqlServer.Management.Dts.DtsTransferProvider.ExecuteTransfer()
at Microsoft.SqlServer.Management.Smo.Transfer.TransferData()
at Microsoft.SqlServer.Dts.Tasks.TransferObjectsTask.TransferObjectsTask.TransferDatabasesUsingSMOTransfer()
Any help would be appreciated!
Jim
My suggestion is dont use the copy database wizard. Create a full backup of the database on the 2000 server and then restore it on the 2008 server.
If you google "Microsoft.SqlServer.Management.Dts.DtsTransferProvider.ExecuteTransfer Copy Database Wizard" you will find that many many people have gotten this same error or other nearly identical smo errors... no-one appears to have gotten past it.
That's isn't to say its impossible... just, restoring a backup is so much easier then the wizard or troubleshooting the wizard. Good luck.
The copy wizard had missed some security and IIRC it's caused by subtle differences in security tables, principals etc between the 2 versions.
Frankly, the easiest way is to do one of these two:
backup/restore
detach, copy, attach
If you don't have access to the O/S and can't get it, another option is to create the missing role(s) in the background as the copy runs. You have to catch it between the creation of the files and when it tries to reference the roles, but there are a few seconds in which to create them if you keep clicking execute - I managed to create 9 roles.
Unfortunately, you'll end up with the roles in another database too (while yours cannot be used) so those need to be deleted.
Of course, this is only an option when you really can't use the other method.
Though the answer which is using the backup technique solves the problem generally, after facing the same issue several times, I was able to trace down the root of the problem using the Event Viewer of Windows to that the Database Copy wizard, using the SQL Agent, will eventually create a Job for the agent to run, after which the Agent will run using its own credentials (i.e. the credentials that you can look up in Windows Services, in my case, NT Service\SQLAgent$SQL2014)
All you need to do is to go the folder where SQL Server creates DB files (e.g. C:\Program Files\Microsoft SQL Server\MSSQL12.SQL2014\MSSQL\DATA by default for SQL 2014) and give the SQL Agent windows user write/read access on the folder.
The reason can be that a file with the new Database name already exist on the filesystem. We encountered this when we renamed Database X to X_Old, and tried to copy database Y to X. This cannot be done, because database X_Old is still associated with the filename X.
Either delete the conflicting database, or rename the file on the file system.
See http://codecopy.wordpress.com/2012/01/03/error-while-copying-a-database/

Checking a directory contains files or not - tsql

I'm trying to code a mssql job that does something using the files in a specific directory. But I don't know the name of the file / files, they will vary in time.
I've found xp_cmdshell command, but I can not use it because of security reasons
Is there any other way to check directory if it contains txt files or not (and if yes get the names of them) in tsql.
Thanks in advance,
Without access to the xp_ stored procedures, no. The other way would be to create a COM object using sp_OACreate that creates a COM Scripting.FileSystemObject, but again access to this may well be restricted as it's a security issue.
As your describing this as an MSSQL job, I'm assuming this is going to be a scheduled task of some description? If so, your best option is probably going to be creating a standard Windows batch file (.BAT) that's scheduled in SQL Server agent that does the existential checking and passes whatever files are found in to your SQL script via sqlcmd/osql.

Resources