Creating a SQL Use statement for cross server query [duplicate] - sql

This question already has answers here:
Set database name dynamically in SQL Server stored procedure?
(3 answers)
Closed 9 years ago.
How do you create a cross server query use statement to run a select. This is what I have but I cant seem to get anything than 'does not exist'
Thanks!
DECLARE #ServerVar AS NVARCHAR (MAX)
SET #ServerVar = 'servera/server1';
DECLARE #DBVar AS NVARCHAR (MAX)
SET #DBVar = 'db';
Declare #reportVar nvarchar(max);
Set #reportVar = 'USE ' + quotename(#ServerVar) + '.' + quotename(#DBVar);
EXEC (#reportVar);
SELECT * FROM myTable;

You need to link the remote server to your local one. After that you can query remote server from your local one even without using Use command

This is a good time to use a Linked Server and possibly even synonyms and dynamic sql.
See similar post: Set database name dynamically in SQL Server stored procedure?

Related

Passing query string through variable value fails [duplicate]

This question already has answers here:
Use dynamic table name in sql server query
(2 answers)
Closed 7 months ago.
Using Microsoft SQL Server 2015
This works
create procedure Checking1(#SQLQueryString nvarchar(max))
as
begin
select * from MyTable
end
This is not working
create procedure Checking1(#SQLQueryString nvarchar(max))
as
begin
#SQLQueryString
end;
What am I doing wrong?
You need to tell SQL Server to execute your dynamic-SQL
https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-executesql-transact-sql?view=sql-server-ver16
or
https://www.mssqltips.com/sqlservertip/1160/execute-dynamic-sql-commands-in-sql-server/

Run SQL Dynamic using column value [duplicate]

This question already has answers here:
T-SQL: How to use parameters in dynamic SQL?
(4 answers)
sql stored procedure argument as parameter for dynamic query
(2 answers)
SQL Server 2017 - How to pass a parameter in a SELECT inside a dynamic SQL
(1 answer)
Closed last year.
I am using dynamic SQL.
I inserted a select statement into one row from #example, I want to call that select statement and run it with dynamic SQL, my select stored has a variable call #NumOrder
create table #example(id int, description varchar(1000))
insert into #example(id, description)
values(1, 'select case when name=''Carlos'' then ''Pass'' else ''FAIL'' from server.dbo.person where number = #NumOrder')
declare #NumOrder int, #SQL nvarchar(max)
set #NumOrder=2621
set #SQL='description'
--here is where I want to call my query and is failing
--once I filled #NumOrder I want to display the results
exec(#SQL)
I want to run this dynamic SQL using a row stored into the temp table, I know that I can put the complete select statement into the #SQL and works but I want to know if there is a way to call the select statement in a row stored from a table. Is there a way to do this?

Can I use a variable as the value of the option AUDIT_GUID for the CREATE SERVER AUDIT statement?

I am trying to make the Audit_GUID value in the CREATE SERVER AUDIT command dynamic by using the NEWID() function in SQL. Below is my SQL script to do this:
USE [master]
GO
DECLARE #newGUID as uniqueidentifier
SET #newGUID = NEWID()
CREATE SERVER AUDIT Audit_Select_Queries -- Name of the Audit(unique for a Server)
TO FILE
( FILEPATH = N'XXXX' -- Folder to Store Audit Files at
,MAXSIZE = 0 MB -- 0 = UNLIMITED
,MAX_ROLLOVER_FILES = 2147483647 -- Max possible number of Files
,RESERVE_DISK_SPACE = OFF
)
WITH
( QUEUE_DELAY = 1000 -- Delay Audit actions by this time for completion
,ON_FAILURE = CONTINUE -- Database operation is more important than Audit
,AUDIT_GUID = #newGUID -- UUID of the Audit (unique for a server)
)
ALTER SERVER AUDIT Audit_Select_Queries WITH (STATE = OFF)
GO
But I get a syntax error near #newGUID saying "Incorrect syntax near '#newGUID'"
Please let me know what am I doing wrong.
EDIT: I am working on Microsoft SQL Server 2012
No ...
CREATE SERVER AUDIT is a statement – so AUDIT_GUID isn't a 'parameter' in the same way that a SQL Server parameter of a stored procedure is a parameter. If you're familiar with other languages, you could consider CREATE SERVER AUDIT as a 'special form' and, as such, you simply need to remember that it doesn't accept variables for that option.
I can understand why that's confusing as, for example, the BACKUP statement(s) do allow variables for certain 'parameters' ("options"), namely the name of the database; e.g. this is perfectly valid T-SQL:
DECLARE #databaseName nvarchar = "insert_name_of_database_here";
BACKUP DATABASE databaseName
...
For clarifying these types of questions, just consult Microsoft's documentation for the relevant version of SQL Server if you can't remember whether some parameters or options accept variables or not. [You can easily open the relevant documentation from SSMS by highlighting the statement, built-in procedure, etc. and hitting F1 on your keyboard.]
But if You're Willing to Dynamically Generate the T-SQL ...
Here's how you can use dynamic SQL – via EXECUTE or sp_executesql – to do what you're trying to do:
DECLARE #dynamicSql nvarchar(1000);
SELECT #dynamicSql = 'CREATE SERVER AUDIT
...
AUDIT_GUID = ''' + CAST(#newGUID AS nvarchar(255)) + ''''
+ '...' + ...,
EXEC sp_executesql #dynamicSql;

Passing Multiple Parameters to SQL Server [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Parameterizing an SQL IN clause?
Comma-separated value insertion In SQL Server 2005
I'm trying to search in my database using where in clause, but my string is in follow format:
'233052,57516351,254689'
I need to do an consult in my database using the following query:
SELECT * FROM myTable WHERE field IN (#list_string)
How I do to make this action?
Use Table-valued parameters, introduced in SQL Server 2008.
These let you pass in a table structure that you can use to query on.
For other options, I suggest reading Arrays and Lists in SQL Server, by Erland Sommarskog.
I've been using Itai Goldstein's Split function for years for this very situation. You could then do the following:
SELECT *
FROM [myTable]
WHERE [field] IN (
SELECT [Data]
FROM [dbo].[Split] (#list_string, ',')
);
Try EXEC of sql statement concatenation:
declare #sql varchar(200)
set #sql='SELECT * FROM myTable WHERE field IN ('+#list_string+')'
exec(#sql)

Dynamically creating the IN clause in a stored procedure [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Need help in dynamic query with IN Clause
I am using SQL server 2008 and this is the problem that I am facing. I have a table named Cars with a column Company. Now I have a stored procedure that looks something like this
CREATE PROCEDURE FindCars (#CompanyNames varchar(500))
AS
SELECT * FROM Cars WHERE Company IN (#CompanyNames)
I tried something like this and failed
DECLARE #CompanyNames varchar(500)
SET #CompanyNames = '''Ford'',''BMW'''
exec FindCars #CompanyNames
I dont get any rows returned. When I do the following
DECLARE #CompanyNames varchar(500)
SET #CompanyNames = '''Ford'',''BMW'''
Select #CompanyNames
I get the following result
'Ford','BMW'
and if I replace this value in the select statement inside the stored procedure, it works
SELECT * FROM Cars where Company in ('Ford','BMW')
Thus I think that the stored procedure seems to be treating 'Ford','BMW' as one string rather than an array. Could someone please help me with this. How do I dynamically construct the string/array required in the IN clause of the select statement inside the stored procedure.
You are right, you created one string, and that is being processed as a list of strings that contains one string. The commas are just characters in that one string. The only equivilent to an array in SQL Server is a table.
For example; WHERE x IN (SELECT y FROM z).
For this reason many people create a SPLIT_STRING() function that returns a table of items from a given comma delimitted string...
WHERE x IN (SELECT item FROM dbo.split_string(#input_string))
There are many ways to implement that split string. Some return strings, some cast to integers, some accept a second "delimiter" parameter, etc, etc. You can search the internet for SQL SERVER SPLIT STRING and get many results - Including here in StackOverflow.
An alternative is to use dynamic SQL; SQL that writes SQL.
SET #sql = 'SELECT * FROM x WHERE y IN (' + #input_string_list + ')'
SP_EXECEUTESQL #sql
(I recommend SP_EXECUTESQL over just EXEC because the former allows you to use parameterised queries, but the latter does not.)