See this...
SELECT *
INTO #WL_Klijenti
FROM OPENROWSET ('SQLOLEDB','Server=(local);TRUSTED_CONNECTION=YES;','SET
FMTONLY OFF; SET NOCOUNT ON; EXEC
WBANKA_KBBL2.dbo.sp_kbbl_WachLista_Priprema ''2017.09.30'', ''2017.09.30'',
0')
AS tbl
The part : EXEC WBANKA_KBBL2 should be replaced with the current db used, so that the user does not have to specify it manualy.
I had an idea of a procedure with an output parameter which will return current database and store it in a variable and this was my try:
SP Looks like this:
CREATE procedure dbo.getCurrentDB
(
#dbName varchar(30) OUTPUT
)
AS
BEGIN
set #dbName = (select db_name())
--select #dbName
END
go
How can I pass my current db used to the procedure call, instead of specifying it manually?
EDIT:
When I run it like this I receive A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations
declare #dbName varchar(30)
exec getCurrentDB #dbName output
DECLARE #ORS varchar(MAX);
SELECT #ORS = 'Server=(local);TRUSTED_CONNECTION=YES;','SET
FMTONLY OFF; SET NOCOUNT ON; exec
select ' + QUOTENAME([name] + '.dbo.sp_kbbl_WachLista_Priprema
''2017.09.30'', ''2017.09.30'',
0')
FROM sys.databases
WHERE [name] = #dbName
SELECT *
INTO #WL_Klijenti
FROM OPENROWSET ('SQLOLEDB',#ORS)
AS tbl;
Related
CREATE PROCEDURE [dbo].[sp_HeatMap_Paper]
#Grade varchar(150)=NULL,
#Site varchar(250)=NULL,
#TRef varchar(15)=NULL
AS
BEGIN
SET NOCOUNT ON;
DECLARE #uregref varchar(50), #regTID varchar(8),
#testValue varchar(80), #testResultID int,
#lowerL1 varchar(20), #upperL1 varchar(20),
#lowerL2 varchar(20), #upperL2 varchar(20)
BEGIN TRANSACTION
BEGIN TRY
DELETE FROM HeatMap;
select top 1 #uregref = URegRef from NA_PAPER_HEAT_MAP where RSDESCRIPTION= #Grade and BOX_PLANT1= #Site;
select #regTID = RegTID from REGKEY where URegRef = #uregref;
select #testValue=TestResult,#testResultID=Result_ID from RESULTDATA where RegTID=#regTID and TRef=#TRef;
SELECT #lowerL1=Lower, #upperL1=Upper from ResultLimit WHERE Priority = 1 and Result_Id=#testResultID;
SELECT #lowerL2=Lower, #upperL2=Upper from ResultLimit WHERE Priority = 2 and Result_Id=#testResultID;
Insert into HeatMap (Grade,Site,TestValue,TRef,LowerLimitL1,UpperLimitL1,LowerLimitL2,UpperLimitL2)
values (#Grade,#Site,#testValue,#TRef,#lowerL1,#upperL1,#lowerL2,#upperL2)
COMMIT TRANSACTION
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION
Return Error_Message()
END CATCH
END
GO
I want to pass a view name into this stored procedure, here 'NA_PAPER_HEAT_MAP' is the view instead of this I want to pass a parameter #viewName
You can build dynamic SQL and execute it using sys.sp_executesql to execute it.
I'll give you an example for how to use it.
CREATE PROCEDURE usp_selectView
#id INT,
#viewName NVARCHAR(1000)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #sql NVARCHAR(MAX), #paramDef NVARCHAR(MAX);
-- build dynamic SQL
-- you can build whatever SQL you want. This is just an example
-- make sure you sanitize #viewName to avoid SQL injection attack
SET #sql = 'SELECT * FROM ' + #viewName + ' WHERE Id = #selectedId';
-- dynamic SQL parameter definition
SET #paramDef = '#selectedId INT';
-- here, execute the dynamic SQL
EXEC sys.sp_executesql #sql, #paramDef, #selectedId = #id
END
I try to select data from a table of another database in my storedprocedure and the name of the other database is given by parameter. I get an error message:
'Invalid object name [#DbName].dbo.Setup'.
CREATE PROCEDURE [dbo].[spUndeliverableOrders]
#DbName sysname
AS
BEGIN
SET NOCOUNT ON;
DECLARE #Sortfield nvarchar(50)
SET #Sortfield = (SELECT COALESCE(Text, 'ToDoListeDatum') AS SortField FROM [#DbName].dbo.Setup WHERE label like 'ComboBoxSetupBatchReihenfolge')
END
GO
Can someone help me to solve this problem?
Like #ThomasSchremser said:
DECLARE #sqlquery varchar(1000)
SET #sqlquery = '(SELECT COALESCE(Text, ''ToDoListeDatum'') AS SortField FROM ['+#DbName+'].dbo.Setup WHERE label like ''ComboBoxSetupBatchReihenfolge'')'
It is upto you to decide weither you what to populate a table/variable with the results.
Either use:
insert into #table(column) exec #sqlquery...
or
sp_executesql #sqlquery...
You need to use dynamic query as below
CREATE PROCEDURE [dbo].[spUndeliverableOrders]
#DbName sysname
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE #Str varchar(max)
CREATE TABLE #Result(Res VARCHAR(MAX))
SET #Str = 'insert into #Result SELECT TOP 1 COALESCE(Text, ''ToDoListeDatum'') AS SortField FROM ['+#DbName+'].dbo.Setup WHERE label like ''ComboBoxSetupBatchReihenfolge'''
exec(#str)
select Res from #Result
END
Modified per your script:
DECLARE #Str varchar(max)
CREATE TABLE #Result(Res VARCHAR(MAX))
SET #Str = ' SELECT TOP 1 COALESCE(Text, ''ToDoListeDatum'') AS SortField FROM ['+#DbName+'].dbo.Setup WHERE label like ''ComboBoxSetupBatchReihenfolge'''
insert into #Result
EXEC(#Str)
I've created a stored procedure where I want to pass the #DB through a USE command. I know I can define dynamically the correct path for the table with the name of the DB (e.g. ... '+ #DB +' .dbo.tAnalysisResult' ) but I have several inner joins with many tables on the same database so I'd like to define the DB only once at the beginning.
Any help will be highly appreciated. Below my query which currently doesn't work:
USE [DB_Research]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].sp_test1 #DB VARCHAR(300), #OUTCOME INT OUTPUT
AS
SET NOCOUNT ON
EXECUTE ('USE' + #DB)
BEGIN TRY
SELECT #OUTCOME = (select SUM(ResultSID) from tAnalysisResult)
END TRY BEGIN CATCH
-- If error encountered, display it
SELECT #OUTCOME = '0, line: ' + CAST(ERROR_LINE() AS VARCHAR(MAX)) + ', msg:' + ERROR_MESSAGE()
END CATCH
SET NOCOUNT OFF
-- Execute the stored procedure
declare #OUTCOME INT
exec sp_test1 'Loss_DB', #OUTCOME OUTPUT
Print(#OUTCOME)
Select * from dbname..schemaname.tablename
My Dynamic SQL queries have been placed inside a table. I want to read these from the table (in SQL server), do a parameter substitution, then execute the dynamic query.
i.e. Column GetFieldServerSQL contains the following:
SELECT top 1 Tenancy.LeadName
FROM Tenancy
RIGHT OUTER JOIN Property ON Tenancy.KeyProperty = Property.KeyProperty
WHERE (Tenancy.EndDate IS NULL) and Property.KeyProperty = #PropertyID
This is what I have tried:
declare #sql nvarchar(1000)
declare #sql2 nvarchar(1000)
declare #res nvarchar(1000)
declare #result nvarchar(1000)
set #sql = 'SELECT [GetFieldServerSQL]
FROM [SVSCentral].[dbo].[SVSSurvey_ExternalField] where ID=5'
exec #res = sys.sp_executesql #sql
print #res
This returns my query in the Results window, but I want it as a variable. #res only contains a 0 (for success)
Once I have it as a variable, I want to do a substitution. Something like:
set #sql2 = REPLACE(#result,'#propertyID','1003443')
(supposing #result is where my results is stored)
And then execute it:
exec (#sql2)
Instead of doing this:
exec #res = sys.sp_executesql #sql
You need to insert the results into a table, then select from that table, like this:
DECLARE #resTable TABLE (res nvarchar(1000))
INSERT INTO #resTable (res)
exec (#sql)
SELECT #res=res from #resTable
print #res
This is my Store Procedure :
ALTER PROC [dbo].[Details]
#name nvarchar(20)
AS
BEGIN
SELECT Id FROM Client WHERE name in (#Name)
END
If i am passing one value output is Coming:
Like this i am passing:
EXEC [dbo].[Details] 'Monday'
For Two values Like this :
If i am passing two value output not is Coming:
To get this in which way i need to send parameter
currently I am passing Two parameter like This
EXEC [dbo].[Details] ''Monday','Wipro'';
Thank u in advance
You can try this code to extract table from your parameter:
declare #sql nvarchar(max)=
'abc,def,ghi,jkl'
set #sql = replace(#sql,',','''),(''')
set #sql = 'select *
from (values ('''+#sql+''')
) a ( Value )
'
PRINT(#sql)
exec sp_executesql #sql
Then use execution result with IN-condition. You can configure this part with any delimiter.
Try this one:
ALTER PROCEDURE dbo.[Details]
#name NVARCHAR(30)
AS
DECLARE #Sql VARCHAR(MAX)
SET #name = REPLACE(#name,',',''',''')
SET #Sql = 'SELECT
*
FROM table1
WHERE username IN
(
''' + #name + '''
)'
EXEC (#Sql)
EXEC [dbo].[Details] 'mohan,prashant'