I have an error during the execution of my proc that I must declare my variable while this last variable is well declared
because I declared my variables in the proc
Proc Syntax
USE [Test]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[ADMIN_D] #LNK_Name nvarchar(60) ,#bdd varchar(50) ,#PS VARCHAR(80), #SCH SYSNAME = 'dbo'
AS
Declare #sqlm varchar(max)
Declare #sql1 nvarchar(max)
Declare #sql nvarchar(max)
Declare #sqlZ varchar(max)
Declare #LINK nvarchar(max)
Declare #LINK1 nvarchar(max)
Declare #LINK2 varchar(max)
--Declare #bdd varchar(35)
Declare #Login varchar(80)
Declare #Datetime datetime
SET NOCOUNT ON;
IF (ORIGINAL_LOGIN() IN (''))
BEGIN;
PRINT 'Déploiement interdit - Contactez l''équipe SQL ';
RETURN;
END;
SET #Datetime = Getdate()
SET #Login = system_user
SELECT #sql = Definition
FROM sys.procedures p
INNER JOIN sys.sql_modules m ON p.object_id = m.object_id
where name = #PS and p.schema_id = SCHEMA_ID(#SCH)
--BEGIN DISTRIBUTED TRAN
raiserror('--- Alim Z_CODESOURCE de Prod',0,1) WITH NOWAIT
SET #sqlZ = 'EXEC dbo.Z_CODESOURCE_Alim #NOM_OBJET = ''' + #PS + ''''
SET #LINK = N'EXEC (#sqlZ) AT ' + QUOTENAME(#LNK_Name);;
EXEC sp_executesql #LINK;
SET NOCOUNT OFF
IF EXISTS (SELECT TOP 1 1 FROM ADMIN_DEPLOY_BLOCK WHERE NOM_PS = #PS AND Nom_Schema = #SCH)
BEGIN
SELECT 'DEPLOIEMENT INTERDIT PAR ' + ACTEUR + '. RAISON: ' + RAISON
FROM ADMIN_DEPLOY_BLOCK
WHERE NOM_PS = #PS
AND Nom_Schema = #SCH;
PRINT 'Pas de déploiement !'
END
ELSE
BEGIN TRY
SET #sqlm = ' USE [' + #bdd + '];DELETE FROM METADATA WHERE NAME = '''+#PS+''''
SET #LINK = N'EXEC (#sqlm) AT ' + QUOTENAME(#LNK_Name);
EXEC sp_executesql #LINK ;
SET #sql1 = 'IF EXISTS (SELECT * FROM sys.objects WHERE type IN (''P'', ''FN'') AND name = '''+#PS+''' AND schema_id = ( select schema_id from sys.schemas WHERE name=''' + #SCH + ''' )) DROP PROCEDURE ' + #SCH + '.' + #PS
SET #sql1 = 'IF EXISTS (SELECT * FROM sys.objects WHERE type IN (''P'', ''FN'') AND name = '''+#PS+''') DROP PROCEDURE '+#PS
SET #sql1 = REPLACE(#sql1,'''','''''')
SET #sql1 = 'USE [' + #bdd + ']; EXEC(''' + #sql1 + ''')'
SET #LINK1 = N'EXEC (#sql1) AT ' + QUOTENAME(#LNK_Name) ;
EXEC sp_executesql #LINK1 ;
SET #sql = REPLACE(#sql,'''','''''')
SET #sql = 'USE [' + #bdd + ']; EXEC(''' + #sql + ''')'
SET #LINK2 = N'EXEC (#sql) AT ' + QUOTENAME(#LNK_Name) ;
EXEC sp_executesql #LINK2 ;
INSERT INTO LOG_DEPLOYPS (LOGIN, PS, DAT) values (#login, #PS, #datetime)
Print ''
Print ''
Print 'Déploiement effectuée avec succès'
--COMMIT TRAN
END TRY
BEGIN CATCH
Print ''
Print ''
Print 'Une erreur est survenue: ' + CAST(##ERROR AS VARCHAR(255))
SELECT
#PS AS ProcedureName
,ERROR_NUMBER() AS ErrorNumber
,ERROR_SEVERITY() AS ErrorSeverity
,ERROR_STATE() AS ErrorState
,ERROR_PROCEDURE() AS ErrorProcedure
,ERROR_LINE() AS ErrorLine
,ERROR_MESSAGE() AS ErrorMessage;
--ROLLBACK TRAN
END CATCH
END
Execute Proc
USE [Test]
GO
DECLARE #return_value int
EXEC #return_value = [dbo].[ADMIN_D]
#bdd = N'PROD',
#PS = N'SP_login',
#LNK_Name=N'uat-link'
SELECT 'Return Value' = #return_value
GO
Someone who can help me please
enter image description here
Run stored procedure on linked server (linked server name as variable)
The problem is these lines (and other places later on where you use the same pattern):
SET #LINK = N'EXEC (#sqlZ) AT ' + QUOTENAME(#LNK_Name);;
EXEC sp_executesql #LINK;
The sp_executesql function creates a new execution context that doesn't know about the #sqlZ variable. To get around this, there are additional arguments you must pass to the function to set up the variables and their values.
Related
I would like to create a temptable that will hold the result of this query:
set #sql = 'use ' + #dbname + '; select db_name() , name from sys.tables where is_ms_shipped = 0 and type_desc = ''USER_TABLE'' '
exec (#sql)
Here is the full query I have:
declare #minx int = 0
declare #maxx int = (select max(id) from #DBS)
declare #sql nvarchar(1000)
declare #dbname varchar (130)
declare #count int
Select *
from #DBS
while (#count is not null
and #count <= #maxx)
begin
select #dbname = dbname
from #DBS where id = #count
print 'id = ' + convert (varchar, #count) + ' dbname = ' + #dbname
set #sql = 'use ' + #dbname + '; select db_name() , name from sys.tables where is_ms_shipped = 0 and type_desc = ''USER_TABLE'' '
exec (#sql)
set #count = #count + 1
break
end;
I have tried so many things and always getting error messages.
Anybody could give me an insight?
Not sure how you populate #DBS but:
CREATE TABLE #tables(db sysname, table_name sysname);
DECLARE #dbs cursor,
#context nvarchar(1000),
#sql nvarchar(max);
SET #sql = N'INSERT #tables(db, table_name)
SELECT DB_NAME(), name
FROM sys.tables
WHERE type = ''U'' AND is_ms_shipped = 0;';
SET #dbs = CURSOR FOR SELECT QUOTENAME(dbname)
+ N'.sys.sp_executesql' FROM #DBS;
OPEN #dbs;
FETCH NEXT FROM #dbs INTO #context;
WHILE ##FETCH_STATUS = 0
BEGIN
EXECUTE #context #sql;
FETCH NEXT FROM #dbs INTO #context;
END
SELECT db, table_name FROM #tables;
Also see this related question.
I want to run my query multiple times, based on values in array.
I came quite close, but I don't know how to call my query through the iteration. The examples I find online state 'Exec procedure' but then don't show the content of a procedure, so I don't know how to let a query refer to a procedure the right way.
In my code below I first have show the iteration and then I have a procedure that I named QueryIWantToUse.
INSERT INTO #ids (id)
SELECT 'CTMContactOrigin' UNION
SELECT 'PMMParameters' UNION
SELECT 'TAXTABLE'
DECLARE #i INT
DECLARE #cnt INT
SELECT #i = MIN(idx) - 1, #cnt = MAX(idx) FROM #ids
WHILE #i < #cnt
BEGIN
SELECT #i = #i + 1
DECLARE #id = SELECT id FROM #ids WHERE idx = #i
EXEC QueryIWantToUse #id
END
--QueryIWantToUse:
DECLARE #Table nvarchar(max),
#EntityName nvarchar(max),
#EntityLeaf nvarchar(max),
#EntityCode nvarchar(10),
#CodeRefTable_EN nvarchar(max),
#CodeRefTable_MS nvarchar(max),
#sql nvarchar(max);
SET #Table = #id -- Here I want the array values to be used somehow
SET #EntityName =
(SELECT ENTITYTABLE FROM [Tobias_AX_MasterZWS_test].[dbo].[DMFENTITY] --MASTER DB NAAM
WHERE [Tobias_AX_MasterZWS_test].[dbo].[DMFENTITY].ENTITYTYPENAME = #Table
)
SET #EntityLeaf = #EntityName + '_Leaf'
SET #EntityCode =
(SELECT Code FROM [MDS_AX2012_ZWS].[mdm].[tbl_1_2_EN]
WHERE [MDS_AX2012_ZWS].[mdm].[tbl_1_2_EN].[NAME] = #EntityName
)
SET #CodeRefTable_EN = 'tbl_'+#EntityCode +'_EN'
SET #CodeRefTable_MS = 'tbl_'+#EntityCode +'_MS'
DECLARE #TableName_EN sysname = #CodeRefTable_EN,
#TableName_MS sysname = #CodeRefTable_MS;
SET #sql = N'SELECT * FROM [MDS_AX2012_ZWS].[dbo].[AxVersionTable] WHERE [MDS_AX2012_ZWS].[dbo].[AxVersionTable].EntityName ' + --change to DELETE FROM after testing
N' = ' +
quotename(#EntityName, '''') +
N';';
EXEC sp_executesql #sql;
SET #sql = N'SELECT * FROM [MDS_AX2012_ZWS].[STG].' + quotename(#EntityLeaf) --change to DROP TABLE after testing
EXEC sp_executesql #sql;
SET #sql = N'SELECT * FROM [MDS_AX2012_ZWS].[MDM].' + quotename(#TableName_EN) + 'WHERE VERSION_ID <> 1337'; --change to DELETE FROM after testing
EXEC sp_executesql #sql;
SET #sql = N'SELECT * FROM [MDS_AX2012_ZWS].[MDM].' + quotename(#TableName_MS) + 'WHERE VERSION_ID <> 1337'; --change to DELETE FROM after testing
EXEC sp_executesql #sql;
SET #sql = N'SELECT * FROM [MDS_AX2012_ZWS].[MDM].' + quotename(#TableName_EN); --change to DROP TABLE after testing
EXEC sp_executesql #sql;
SET #sql = N'SELECT * FROM [MDS_AX2012_ZWS].[MDM].' + quotename(#TableName_MS); --change to DROP TABLE after testing
EXEC sp_executesql #sql;
SET #sql = N'SELECT * FROM [Tobias_AX_MasterZWS_test].[dbo].' + quotename(#EntityName); --change to TRUNCATE TABLE after testing
EXEC sp_executesql #sql;
SET #sql = N'SELECT * FROM [Tobias_AX_MasterZWS_test].[dbo].[DMFENTITY] WHERE [Tobias_AX_MasterZWS_test].[dbo].[DMFENTITY].EntityTable ' + --change to DELETE FROM after testing
N' = ' +
quotename(#EntityName, '''') +
N';';
EXEC sp_executesql #sql;
Any suggestions how to link the iteration with the procedure?
Hi I have developed a stored procedure in which I declared the a table variable called #TEMP_TABLE but for this line
SET #SQL1 = 'UPDATE PO_STAGE set PO_STAGE.ISVALID = ''N''
FROM ERP_ADMIN.'+#STAGE_TABLE+' PO_STAGE, #TEMP_TABLE TMP
where PO_STAGE.ERP_PO_ID = TMP.ERP_POID'
exec (#SQL1)
I am getting "Must declare the table variable "#TEMP_TABLE"." error.
Please help me in this regards.Below is the code for Stored Procedure.
CREATE PROCEDURE [ERP_ADMIN].[VALIDATE_PURCHASE_ORDER]
#STAGE_TABLE nvarchar(50)
-- #errorProperty nvarchar(50) output,
-- #errorValue nvarchar(120) output
AS
BEGIN
SET NOCOUNT ON;
DECLARE #rule INTEGER
DECLARE #approvalcheckingrecord VARCHAR(200)
DECLARE #APP_VALIDFROMDATE DATETIME,
#APP_VALIDTODATE DATETIME,
#numUpdated INTEGER,
#numInserted INTEGER,
#systodate VARCHAR(160),
#SQL1 [nvarchar](1200),
#SQL2 [nvarchar](1200),
#SOUCOL [nvarchar](200)
-- SELECT #systodate = CONVERT(VARCHAR(23), ERP_ADMIN.GETCURRENTDATE(), 110) +' '+ CONVERT(VARCHAR(23), ERP_ADMIN.GETCURRENTDATE(), 108)
--SELECT #systodate = CONVERT(VARCHAR(23), GETDATE(), 110) +' '+ CONVERT(VARCHAR(23), GETDATE(), 108)
SET #SQL1 = ''
SET #SQL1 = 'SELECT ERP_SOURCE_COLUMN
FROM [ERP_ADMIN].[ERP_STAGE_PROP_MAPPING] where [ERP_SOURCE_TABLE] = '''+#STAGE_TABLE+''' and [ERP_REPORT_COLOMNS] = ''Y'''
-- PRINT #SQL1
SET #SQL2 = 'DECLARE rpt_cursor CURSOR GLOBAL FOR ' + #SQL1
exec (#SQL2)
DECLARE #SOURCE_COLOMN nvarchar(80)
SET #SOUCOL = ''
OPEN rpt_cursor
WHILE (0 = 0)
--begin of while
BEGIN
FETCH NEXT FROM rpt_cursor INTO #SOURCE_COLOMN
IF (##FETCH_STATUS = -1)
BREAK
IF (#SOUCOL = '')
SET #SOUCOL = 'convert(nvarchar(255),ISNULL('+#SOURCE_COLOMN+',''''))+'',''+'
ELSE
SET #SOUCOL = #SOUCOL + 'convert(nvarchar(255),ISNULL('+#SOURCE_COLOMN+',''''))+'',''+'
END
CLOSE rpt_cursor
DEALLOCATE rpt_cursor
PRINT #SOUCOL
DECLARE #TEMP_TABLE TABLE (
ERP_POID nvarchar(50),
ERRORCD nvarchar(50),
ERRORMSG nvarchar(120)
)
SET #SQL1 = ''
SET #SQL1 = 'SELECT ERP_SOURCE_COLUMN
FROM [ERP_ADMIN].[ERP_STAGE_PROP_MAPPING] where [ERP_SOURCE_TABLE] = '''+#STAGE_TABLE+''' and [ERP_REPORT_COLOMNS] = ''Y'''
SET #SQL1 = 'SELECT [ERP_SOURCE_TABLE]
,[ERP_SOURCE_COLUMN]
,[ERP_MANDATORY_CHECK]
,[ERP_DATA_CHECK]
,[ERP_ERROR_PROPERTY1]
,[ERP_ERROR_VALUE1]
,[ERP_ERROR_PROPERTY2]
,[ERP_ERROR_VALUE2]
FROM [ERP_ADMIN].[ERP_STAGE_PROP_MAPPING] where [ERP_SOURCE_TABLE] = '''+#STAGE_TABLE+''' and ([ERP_MANDATORY_CHECK] IN (''K'',''Y'') or [ERP_DATA_CHECK] IN (''D'',''N''))'
PRINT #SQL1
SET #SQL2 = 'DECLARE stage_cursor CURSOR GLOBAL FOR ' + #SQL1
/** DECLARE stage_cursor CURSOR LOCAL FOR
/****** Script for SelectTopNRows command from SSMS ******/
SELECT [ERP_SOURCE_TABLE]
,[ERP_SOURCE_COLUMN]
,[ERP_MANDATORY_CHECK]
,[ERP_DATA_CHECK]
,[ERP_ERROR_PROPERTY1]
,[ERP_ERROR_VALUE1]
,[ERP_ERROR_PROPERTY2]
,[ERP_ERROR_VALUE2]
FROM [ERP_ADMIN].[ERP_STAGE_PROP_MAPPING] where [ERP_SOURCE_TABLE] = '+#STAGE_TABLE+' and ([ERP_MANDATORY_CHECK] IN ('K','Y') or [ERP_DATA_CHECK] IN ('D','N')) **/
exec(#SQL2)
DECLARE #CUR_SOURCE_TABLE [nvarchar](120),
#CUR_SOURCE_COLUMN [nvarchar](120),
#CUR_MANDATORY_CHECK [nvarchar](20),
#CUR_DATA_CHECK [nvarchar](20),
#CUR_ERROR_PROPERTY1 [nvarchar](50),
#CUR_ERROR_VALUE1 [nvarchar](120),
#CUR_ERROR_PROPERTY2 [nvarchar](50),
#CUR_ERROR_VALUE2 [nvarchar](120)
OPEN stage_cursor
WHILE (0 = 0)
--begin of while
BEGIN
FETCH NEXT FROM stage_cursor INTO
#CUR_SOURCE_TABLE,
#CUR_SOURCE_COLUMN,
#CUR_MANDATORY_CHECK,
#CUR_DATA_CHECK,
#CUR_ERROR_PROPERTY1,
#CUR_ERROR_VALUE1,
#CUR_ERROR_PROPERTY2,
#CUR_ERROR_VALUE2
IF (##FETCH_STATUS = -1)
BREAK
SET #SQL1 = ''
SET #SQL2 = ''
PRINT #CUR_SOURCE_COLUMN
-- IF(#CUR_SOURCE_COLUMN = 'ERP_PO_DOCNUMBER')
IF (#CUR_MANDATORY_CHECK = 'Y' OR #CUR_MANDATORY_CHECK = 'K')
BEGIN
-- SET #SQL1 = 'SELECT ''aaa'' as column1, ERP_PO_DOCNUMBER as column2
-- from PURCHASE_ORDER_STAGE where '+ #CUR_SOURCE_COLUMN +' IS NULL'
SET #SQL1 = 'SELECT ERP_PO_ID, '''+#CUR_ERROR_PROPERTY1+''' as column1,'+#SOUCOL+'''|1| ERR_01 '''''+#CUR_ERROR_VALUE1+'''+'' or null in input Worksheet'' as column2
from [ERP_ADMIN].'+#STAGE_TABLE+' where '+ #CUR_SOURCE_COLUMN +' IS NULL'
PRINT #SQL1
INSERT INTO #TEMP_TABLE
exec (#SQL1)
END
IF (LTRIM(RTRIM(#CUR_DATA_CHECK)) = 'D')
BEGIN
-- SET #SQL1 = 'SELECT ''aaa'' as column1, ERP_PO_DOCNUMBER as column2
-- from PURCHASE_ORDER_STAGE where '+ #CUR_SOURCE_COLUMN +' IS NULL'
SET #SQL1 = 'SELECT ERP_PO_ID, '''+#CUR_ERROR_PROPERTY2+''' as column1,'+#SOUCOL+'''|1| ERR_01 '''''+#CUR_ERROR_VALUE2+'''+'' in the input Worksheet'' as column2
from [ERP_ADMIN].'+#STAGE_TABLE+' where isdate('+ #CUR_SOURCE_COLUMN +') =0'
PRINT #SQL1
INSERT INTO #TEMP_TABLE
exec (#SQL1)
END
IF (LTRIM(RTRIM(#CUR_DATA_CHECK)) = 'N')
BEGIN
PRINT #CUR_SOURCE_COLUMN
SET #SQL1 = 'SELECT ERP_PO_ID, '''+#CUR_ERROR_PROPERTY2+''' as column1,'+#SOUCOL+'''|1| ERR_01 '''''+#CUR_ERROR_VALUE2+'''+'' in the input Worksheet'' as column2
from [ERP_ADMIN].'+#STAGE_TABLE+' where isnumeric('+ #CUR_SOURCE_COLUMN +') =0'
PRINT #SQL1
INSERT INTO #TEMP_TABLE
exec (#SQL1)
END
END
CLOSE stage_cursor
DEALLOCATE stage_cursor
SET #SQL1 = ''
SET #SQL1 = 'UPDATE PO_STAGE set PO_STAGE.ISVALID = ''N'' FROM ERP_ADMIN.'+#STAGE_TABLE+' PO_STAGE, #TEMP_TABLE TMP where PO_STAGE.ERP_PO_ID = TMP.ERP_POID'
PRINT #SQL1
exec (#SQL1)
/** DECLARE update_stage_cursor CURSOR LOCAL FOR
SELECT ERP_POID FROM #TEMP_TABLE
DECLARE #CURPOID [nvarchar](50)
OPEN update_stage_cursor
WHILE (0 = 0)
--begin of while
BEGIN
FETCH NEXT FROM update_stage_cursor INTO
#CURPOID
IF (##FETCH_STATUS = -1)
BREAK
END
CLOSE update_stage_cursor
DEALLOCATE update_stage_cursor **/
-- SELECT A.ERP_PO_ID FROM ERP_ADMIN.PURCHASE_ORDER_STAGE A, #TEMP_TABLE B where ERP_PO_ID = B.ERP_POID
SELECT ERRORCD, ERRORMSG FROM #TEMP_TABLE
END
GO
You should pass #TEMP_TABLE as parameter. To pass Table parameter you should create table type at first:
IF NOT EXISTS (SELECT 1 FROM sys.types WHERE NAME = 'TEMP_TABLE_TYPE')
CREATE TYPE TEMP_TABLE_TYPE AS TABLE(
ERP_POID nvarchar(50),
ERRORCD nvarchar(50),
ERRORMSG nvarchar(120)
);
And use it:
exec sp_executesql #Sql, N'#TEMP_TABLE TEMP_TABLE_TYPE readonly', #TEMP_TABLE
For epxplonation you can use this link Passing table variable into dynamic sql.
If you find this way not obvious, I advise to use temporary table instead of table varible:
CREATE TABLE #TEMP_TABLE (
ERP_POID nvarchar(50),
ERRORCD nvarchar(50),
ERRORMSG nvarchar(120)
);
What is the best way to achieve this
INSERT INTO #TableName (#ColumnNames)
EXEC sp_executesql #SQLResult;
Where #TableName, #ColumnNames, #SQLResult are varchar variables
I am trying to avoid do a separate insert for each table.
The best way is to write (or generate) all reqiured procedures for all table. 23 tables times 4 procedures (insert, update, delete and select) that can be generated automatically is nothing in dev time and pain compared to the so called "generic solution".
It's a path to poor perfomance, unreadable code, sql injection hazard and countless debuging hours.
First of all I appreciate all your comments. And I agree that SQL dynamic is a pain to debug (Thanks God, management studio has this possibility). And, of course there are hundreds of different solutions
I solved it in this way finally, more or less I try to explain why this solution of SQL dynamic. The client uses xlsx spreadsheets to enter certain data, so I read the spreadsheets and I insert the (data depends on the spreadsheet to insert into the proper table). Later the data in the tables are exported to XML to send a third party sofware.
SET #SEL = N'';
DECLARE sel_cursor CURSOR
FOR (SELECT sc.name as field
FROM sys.objects so INNER JOIN sys.columns sc ON so.[object_id]=sc.[object_id]
WHERE so.name= #TableName and sc.name not in ('InitDate', 'EndDate', 'Version', 'Status'));
SET #SEL = ''; set #i = 0;
OPEN sel_cursor
FETCH NEXT FROM sel_cursor INTO #field
WHILE ##FETCH_STATUS = 0
BEGIN
set #sel = #sel + ', '+ #field
set #i = 1;
FETCH NEXT FROM sel_cursor INTO #field
END
CLOSE sel_cursor;
DEALLOCATE sel_cursor;
SET #SQL = N''
SET #SQL = #SQL + N'SELECT * INTO XLImport FROM OPENROWSET'
SET #SQL = #SQL + N'('
SET #SQL = #SQL + N'''Microsoft.ACE.OLEDB.12.0'''+','
SET #SQL = #SQL + N'''Excel 12.0 Xml; HDR=YES;'
SET #SQL = #SQL + N'Database='+#file +''''+ ','
SET #SQL = #SQL + N'''select * from ['+ #SheetName + '$]'''+');'
EXEC sp_executesql #SQL
SET #SQL = N'';
SET #SQL = #SQL + N'
SELECT '+''''+CAST(#initDate AS VARCHAR(10))+'''' +', '+ ''''+CAST(#endDate AS VARCHAR(10))+''''
+ ', '+ CAST(#version AS VARCHAR(2)) +', ' +''''+#status+''''
+ #SEL
+' FROM DBO.XLImport '
DECLARE cols_cursor CURSOR
FOR (Select COLUMN_NAME From INFORMATION_SCHEMA.COLUMNS where table_name = #tableName);
SET #SEL = ''; set #i = 0;
OPEN cols_cursor
FETCH NEXT FROM cols_cursor INTO #field
WHILE ##FETCH_STATUS = 0
BEGIN
set #sel = #sel + #field + ', '
set #i = 1;
FETCH NEXT FROM cols_cursor INTO #field
END
CLOSE cols_cursor;
DEALLOCATE cols_cursor;
SET #SEL = LEFT(#SEL, LEN(#SEL) - 1) -- remove last ,
SET #SQL = N''
SET #SQL = #SQL + N'SELECT * INTO XLImport FROM OPENROWSET'
SET #SQL = #SQL + N'('
SET #SQL = #SQL + N'''Microsoft.ACE.OLEDB.12.0'''+','
SET #SQL = #SQL + N'''Excel 12.0 Xml; HDR=YES;'
SET #SQL = #SQL + N'Database='+#file +''''+ ','
SET #SQL = #SQL + N'''select * from ['+ #SheetName + '$]'''+');'
EXEC sp_executesql #SQL
SET #SQLString =
N'INSERT INTO '+ #TableName + '('+ #SEL +') ' + #SQL;
EXEC sp_executesql #SQLString
Use EXECUTE sp_executesql #sql, here is example:
create proc sp_DynamicExcuteStore
#TableName varchar(50),
#ColumnNames varchar(50),
#SQLResult varchar(max)
as
declare #sql nvarchar(max) = '
INSERT INTO '+#TableName+' ('+#ColumnNames+')
EXEC sp_executesql '+#SQLResult
EXECUTE sp_executesql #sql
go
create proc sp_test
as
select 'test' + convert(varchar,RAND())
go
CREATE TABLE [dbo].[Test](
[text1] [nvarchar](500) NULL
) ON [PRIMARY]
GO
DECLARE #return_value int
EXEC #return_value = [dbo].[sp_DynamicExcuteStore]
#TableName = N'Test',
#ColumnNames = N'text1',
#SQLResult = N'proc_test'
SELECT 'Return Value' = #return_value
GO
SELECT TOP 1000 [text1]
FROM [test].[dbo].[Test]
I have a problem here, I'm searching in stackoverflow but still not find the best way
i have a stored procedure (SP) like this
DECLARE #table NVARCHAR(max), #SQLQuery NVARCHAR(max)
SET #table = #meta+'_prize4winner'
SET #SQLQuery = 'if exists (Select * from [dbo].' + #table + ' where idCampaignLog =''' + convert(nvarchar, #ID) +''') exec InsertC2CWinner''' + convert(nvarchar, #meta) +''','''+ convert(nvarchar, #ID)+''',null else select ''you lose ''as winStatus'
execute SP_EXECUTESQL #SQLQuery
need help how and where to set the output if I want the output if exist 'YOU WIN' else 'You Lose' thx
The general syntax is like this
DECLARE #retval int
DECLARE #sSQL nvarchar(500);
DECLARE #ParmDefinition nvarchar(500);
DECLARE #tablename nvarchar(50)
SELECT #tablename = N'products'
SELECT #sSQL = N'SELECT #retvalOUT = MAX(ID) FROM ' + #tablename;
SET #ParmDefinition = N'#retvalOUT int OUTPUT';
EXEC sp_executesql #sSQL, #ParmDefinition, #retvalOUT=#retval OUTPUT;
SELECT #retval;