SQL Server stored procedure date - sql-server

I have a procedure which add new data in a table.
The name of the table is in the paramaters.
The error is
The data types varchar(max) and date are incompatible in the add operator.
The date field must be type date.
PROCEDURE
USE [ProposalBuilderDev]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[addLog]
-- Add the parameters for the stored procedure here
#table varchar(max),
#date date,
#version varchar(max),
#process varchar(max),
#level varchar(max),
#message varchar(max),
#stacktrace varchar(max),
#user varchar(max),
#environmentID varchar(max),
#UUID varchar(max),
#UDID varchar(max),
#transactionID int,
#new_identity int OUTPUT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
DECLARE #sql NVARCHAR(MAX);
SET #sql = 'INSERT INTO dbo.' + #table + '([Timestamp], [Version],Process,[Level],[Message],StackTrace,[User],EnvironmentID,UUID,UDID,TransactionID) VALUES (' + #date + ',' + #version + ',' + #process + ','+ #level + ','+ #message + ','+ #stacktrace + ','+ #user + ','+ #environmentID + ','+ #UUID + ','+ #UDID + ',' + #transactionID + ')'
EXEC #sql
SET #new_identity = SCOPE_IDENTITY();
END

Pleas try to use CAST()
... + CAST(#date AS VARCHAR(MAX) + ...
Also, using sp_executesql would be a better and safer approach.
DECLARE #SQL NVARCHAR(MAX);
SET #SQL = ' INSERT INTO dbo.' + #Table;
SET #SQL += ' ([Timestamp], [Version],Process,[Level],[Message],StackTrace,[User],EnvironmentID,UUID,UDID,TransactionID)';
SET #SQL += ' VALUES';
SET #SQL += ' (#p0, #p1, #p2, #p3, #p4, #p5, #p6, #p7, #p8, #p9, #p10);';
EXECUTE sp_executesql
#SQL
, N'#p0 DATE, #p1 VARCHAR(MAX), #p2 VARCHAR(MAX), #p3 VARCHAR(MAX), #p4 VARCHAR(MAX), #p5 VARCHAR(MAX), #p6 VARCHAR(MAX), #p7 VARCHAR(MAX), #p8 VARCHAR(MAX), #p9 VARCHAR(MAX), #p10 VARCHAR(MAX)'
, #p0 = #date
, #p1 = #version
, #p2 = #process
, #p3 = #level
, #p4 = #message
, #p5 = #stacktrace
, #p6 = #user
, #p7 = #environmentID
, #p8 = #UUID
, #p9 = #UDID
, #p10 = #transactionID;
Just specify correct column data types in 3rd line.

Related

Exporting to txt file not allowing more than 255 characters

Below is the script that i have used which shows that i have used BCP process and some shell script to generate the extracts. we need to take the data from sql table and dump as it is in table to flat file. So these can be used to load in hive tables and qlick apps for users to have a look at the data.
ALTER Procedure [dbo].[GenerateEAPExtracts] #tblName NVARCHAR(MAX), #filePath VARCHAR(255)
As
BEGIN
IF OBJECT_ID('tempdb..#Temp1') IS NOT NULL
BEGIN
Drop table #Temp1
END
--DECLARE #tblName NVARCHAR(MAX) = 'BMI.BMI_Invites'
DECLARE #SchemaName NVARCHAR(50)
DECLARE #tbl varchar(100)
DECLARE #DBName varchar(100)
SET #tbl= Replace(#tblname,(Left(#tblname,(LEN(#tblname)-(charindex('.',reverse(#tblname))-1)))),'');
SET #SchemaName= SUBSTRING(#tblName,1,LEN(Left(#tblname,(LEN(#tblname)-(charindex('.',reverse(#tblname))-1))))-1);
DECLARE #SQL NVARCHAR(MAX)=''
DECLARE #SQL1 NVARCHAR(MAX)=''
DECLARE #ColConvert NVARCHAR(MAX)=''
DECLARE #ColName NVARCHAR(MAX)=''
DECLARE #ColName1 NVARCHAR(MAX)=''
DECLARE #ColName2 NVARCHAR(MAX)=''
DECLARE #Dt NVARCHAR(MAX)=''
DECLARE #I INT=1, #COUNT INT;
Create table #Temp1(
ID INT IDENTITY(1,1),
[DBName] [nvarchar](255) NULL,
[TableName] [nvarchar](255) NULL,
[Attributes] [nvarchar](MAX) NULL,
[DataType] [nvarchar](MAX) NULL,
[TceMdf_Dt] [date] NULL
)
SET #SQL = 'INSERT INTO #Temp1 select TABLE_CATALOG as [DBName],
Table_Name as [TableName],
Column_name as [Attributes],
DATA_TYPE as [DataType],
getdate() as [TceMdf_Dt]
from Information_schema.columns where Table_Schema ='''+ #SchemaName +''' AND table_name = '''+#tbl+''''
print #SQL
--EXEC SP_EXECUTESQL #SQL
EXEC(#SQL)
SELECT #SQL1='Select #totCnt= count(1) FROM Information_schema.columns where Table_Schema ='''+ #SchemaName +''' AND table_name = '''+#tbl+''''
print #SQL1
EXECUTE sp_executesql #SQL1, N'#totCnt int OUTPUT', #totCnt=#COUNT OUTPUT
WHILE #I <= #COUNT
BEGIN
SELECT #ColName = Attributes FROM #Temp1 WHERE ID = #I AND [TableName]=#tbl;
SELECT #DBName = DBName FROM #Temp1 WHERE ID = #I AND [TableName]=#tbl;
SELECT #Dt= DataType FROM #Temp1 WHERE ID = #I AND [TableName]=#tbl AND [Attributes]=#ColName
IF #Dt ='Date' or #Dt='Datetime' or #Dt='Decimal' or #Dt='Int' or #Dt='Float' or #Dt='datetime2' or #Dt='Numeric' or #Dt='Real' or #Dt='bit' or #Dt='tinyint'
BEGIN
SET #ColConvert='convert(varchar(25),['+#ColName+'],120)'
--EXECUTE sp_executesql #ColConvert
SET #ColName2 = #ColName2 + ',' + #ColConvert
--EXECUTE sp_executesql #ColName2
END
ELSE
BEGIN
SET #ColName2 = #ColName2 + ',' + '['+#ColName+']'
--EXECUTE sp_executesql #ColName2
END
SET #ColName1 = #ColName1 +''''+''''+','+''''+''''+ #ColName
--EXECUTE sp_executesql #ColName1
SET #I=#I+1;
END
SET #ColName1=RIGHT(#ColName1, LEN(#ColName1) - 3) + ''''''
SET #ColName2=LTRIM(RTRIM(RIGHT(#ColName2, LEN(#ColName2) - 1)))
--print #ColName1
--print #ColName2
--DECLARE #filePath VARCHAR(255)
DECLARE #fileName VARCHAR(255)
DECLARE #sqlCommand VARCHAR(MAX)
DECLARE #sqlCommand1 VARCHAR(MAX)
DECLARE #sqlCommand2 VARCHAR(MAX)
DECLARE #qry nvarchar(max)='(SELECT MaxCDate from '+#DBName+'.config.EAP_Extracts where TableName= '''''+ #tbl +''''')'
print #qry
--exec(#qry)
--SET #filePath = 'C:\'
SET #fileName = #tbl + '_'
+ CONVERT(VARCHAR, GETDATE(), 112) + '.csv'
set #sqlCommand = 'SQLCMD.EXE -S LocalHost -d TCE_WW -E -h -1 -s"|" -W -Q "set nocount on;SELECT ' +#ColName1+ ' ; Select ' +#ColName2+ ' FROM '+#DBName+'.' +#tblName+ ''
print(#sqlCommand)
set #sqlCommand1 =' where TceMdf_Dt > '+ #qry +''
set #sqlCommand2 ='" -o "'+#filePath+#fileName+'" -f 65001'
--declare #chkQry varchar(max) = #sqlCommand+#sqlCommand1+#sqlCommand2
--print(#chkQry)
Update config.EAP_Extracts Set [SqlMaxQuery]=#sqlCommand+#sqlCommand1+#sqlCommand2 where TableName=''+#tbl+''
declare #CommandString varchar(max)= (select distinct 'EXEC xp_cmdshell '+''''+[SqlMaxQuery]+'''' from config.EAP_Extracts where TableName=''+#tbl+'')
--declare #CommandString varchar(max)= 'EXEC xp_cmdshell ' + ''''+#chkQry+''''
print #CommandString
EXEC (#CommandString)
declare #SQLQuery varchar(max)='Update '+#DBName+'.config.EAP_Extracts Set MaxCDate=(Select Max(TceMdf_Dt) from '+ #tblName+') where TableName='''+#tbl+''''
--EXEC xp_cmdshell 'bcp "SELECT ''update_action'',''UserName'',''lastupdate'',''Quote_Num'',''Region'',''ExternalDataReference'',''TceLd_Dt'',''TceMdf_Dt'',''Record_Status'' ; Select LTRIM(RTRIM[update_action]),LTRIM(RTRIM[UserName]),LTRIM(RTRIM[lastupdate]),LTRIM(RTRIM[Quote_Num]),LTRIM(RTRIM[Region]),LTRIM(RTRIM[ExternalDataReference]),convert(varchar(25),LTRIM(RTRIM[TceLd_Dt]),120),convert(varchar(25),LTRIM(RTRIM[TceMdf_Dt]),120),LTRIM(RTRIM[Record_Status]) FROM TCE_WW.BMI.BMI_Invites where TceMdf_Dt > (SELECT MaxCDate from TCE_WW.config.EAP_Extracts where TableName= 'BMI_Invites')" queryout "C:\BMI_Invites_20190722.txt" -T -c -q -y 0 -t"|"'
exec (#SQLQuery)
print(#SQLQuery)
Drop table #Temp1
END

Create dynamic stored procedure for all databases with specific table

I would like to add the following stored procedure to all existing databases which contain the table schichten. All my approaches have failed so I'm looking for help here.
This is my approach:
IF object_id('tempdb.dbo.#database') is not null
drop TABLE #database
GO
CREATE TABLE #database(id INT identity primary key, name sysname)
GO
SET NOCOUNT ON
INSERT INTO #database(name)
SELECT name
FROM sys.databases
WHERE source_database_id is null
ORDER BY name
SELECT * FROM #database
DECLARE #id INT, #cnt INT, #sql NVARCHAR(MAX), #currentDb SYSNAME;
SELECT #id = 1, #cnt = max(id) FROM #database
WHILE #id <= #cnt
BEGIN
BEGIN TRY
SELECT #currentDb = name
FROM #database
WHERE id = #id
IF OBJECT_ID(#currentDb+'.dbo.schichten') IS NOT NULL
CREATE PROCEDURE #currentDb.[dbo].[Ausw_Tabelle_Taxi_Pers_Jahr]
#ColumnName nvarchar(MAX),
#Selector nvarchar(MAX),
#Gesamtergebnis nvarchar(MAX)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #sql1 AS NVARCHAR(MAX),
#ASSelector nvarchar(MAX),
#IFPers nvarchar(MAX);
IF #Selector = 'konz'
BEGIN
SET #ASSelector = 'Taxi'
SET #IFPers=''
END
ELSE
BEGIN
SET #ASSelector = 'Personal'
SET #IFPers = '[name] AS Name,'
END
SET #sql1 = N';WITH temp AS (SELECT *
FROM (
SELECT
ISNULL((DATENAME(m,[datum])+ cast(datepart(yyyy,[datum]) as varchar(5))),0) AS MONTHYEAR,
ISNULL(['+ #Selector +'],0) AS '+ #ASSelector +','+ #IFPers +'
ISNULL((ISNULL([umsum],0) +
ISNULL([sonst_0],0) +
ISNULL([sonst_7],0) +
ISNULL([sonst_16],0) +
ISNULL([sonst_z],0) -
ISNULL([ff],0)),0) AS UMSATZSUMME
FROM [dbo].[schichten]
) AS SOURCE
PIVOT (SUM([UMSATZSUMME]) FOR [MONTHYEAR] IN ('+ #ColumnName + N' )) AS UMSAETZE )
SELECT *, '+ #Gesamtergebnis +' AS Gesamtergebnis FROM temp ORDER BY '+ #ASSelector +''
EXEC sp_executesql #sql
END
END TRY
BEGIN CATCH
END CATCH
SET #id = #id + 1;
END
GO
I am hoping that there is someone who can help me.
You have to execute the create procedure separately, so if you wrap it up into a variable and use exec sp_executesql it should work.
IF object_id('tempdb.dbo.#database') is not null
drop TABLE #database
GO
CREATE TABLE #database(id INT identity primary key, name sysname)
GO
SET NOCOUNT ON
INSERT INTO #database(name)
SELECT name
FROM sys.databases
WHERE source_database_id is null
ORDER BY name
SELECT * FROM #database
DECLARE #id INT, #cnt INT, #sql NVARCHAR(MAX), #currentDb SYSNAME;
SELECT #id = 1, #cnt = max(id) FROM #database
WHILE #id <= #cnt
BEGIN
BEGIN TRY
SELECT #currentDb = name
FROM #database
WHERE id = #id
IF OBJECT_ID(#currentDb+'.dbo.schichten') IS NOT NULL
begin
set #sql = 'CREATE PROCEDURE '+#currentDb+'.[dbo].[Ausw_Tabelle_Taxi_Pers_Jahr]
#ColumnName nvarchar(MAX),
#Selector nvarchar(MAX),
#Gesamtergebnis nvarchar(MAX)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #sql1 AS NVARCHAR(MAX),
#ASSelector nvarchar(MAX),
#IFPers nvarchar(MAX);
IF #Selector = ''konz''
BEGIN
SET #ASSelector = ''Taxi''
SET #IFPers=''''
END
ELSE
BEGIN
SET #ASSelector = ''Personal''
SET #IFPers = ''[name] AS Name,''
END
SET #sql1 = N'';WITH temp AS (SELECT *
FROM (
SELECT
ISNULL((DATENAME(m,[datum])+ cast(datepart(yyyy,[datum]) as varchar(5))),0) AS MONTHYEAR,
ISNULL([''+ #Selector +''],0) AS ''+ #ASSelector +'',''+ #IFPers +''
ISNULL((ISNULL([umsum],0) +
ISNULL([sonst_0],0) +
ISNULL([sonst_7],0) +
ISNULL([sonst_16],0) +
ISNULL([sonst_z],0) -
ISNULL([ff],0)),0) AS UMSATZSUMME
FROM [dbo].[schichten]
) AS SOURCE
PIVOT (SUM([UMSATZSUMME]) FOR [MONTHYEAR] IN (''+ #ColumnName + N'' )) AS UMSAETZE )
SELECT *, ''+ #Gesamtergebnis +'' AS Gesamtergebnis FROM temp ORDER BY ''+ #ASSelector +''''
EXEC sp_executesql #sql1
END'
EXEC sp_executesql #sql
END TRY
BEGIN CATCH
END CATCH
SET #id = #id + 1;
END
GO
Assuming this is a one time need as opposed to a nightly maintenance task, you can use a built-in stored procedure, sys.sp_MSforeachdb, to execute a statement in each database. It is safe to use and has been discussed extensively on the web. However, it is an undocumented feature and can be removed without notice by Microsoft so you don't want to depend on it for recurring tasks.
Create and validate your statement in one database, then use this stored procedure to execute it in all of the databases. ? is the placeholder for the database name.
EXEC sys.sp_MSforeachdb #command1 =
'IF OBJECT_ID(''?.dbo.schichten'') IS NOT NULL
AND OBJECT_id(''?.[dbo].[Ausw_Tabelle_Taxi_Pers_Jahr]'') IS NOT NULL
BEGIN
CREATE PROCEDURE ?.[dbo].[Ausw_Tabelle_Taxi_Pers_Jahr]
#ColumnName nvarchar(MAX),
#Selector nvarchar(MAX),
#Gesamtergebnis nvarchar(MAX)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #sql1 AS NVARCHAR(MAX),
#ASSelector nvarchar(MAX),
#IFPers nvarchar(MAX);
IF #Selector = ''konz''
BEGIN
SET #ASSelector = ''Taxi''
SET #IFPers=''''
END
ELSE
BEGIN
SET #ASSelector = ''Personal''
SET #IFPers = ''[name] AS Name,''
END
SET #sql1 = N'';WITH temp AS (SELECT *
FROM (
SELECT
ISNULL((DATENAME(m,[datum])+ cast(datepart(yyyy,[datum]) as varchar(5))),0) AS MONTHYEAR,
ISNULL([''+ #Selector +''],0) AS ''+ #ASSelector +'',''+ #IFPers +''
ISNULL((ISNULL([umsum],0) +
ISNULL([sonst_0],0) +
ISNULL([sonst_7],0) +
ISNULL([sonst_16],0) +
ISNULL([sonst_z],0) -
ISNULL([ff],0)),0) AS UMSATZSUMME
FROM [dbo].[schichten]
) AS SOURCE
PIVOT (SUM([UMSATZSUMME]) FOR [MONTHYEAR] IN (''+ #ColumnName + N'' )) AS UMSAETZE )
SELECT *, ''+ #Gesamtergebnis +'' AS Gesamtergebnis FROM temp ORDER BY ''+ #ASSelector +''''
EXEC sp_executesql #sql1
END
'

Stored procedure with table name and values as parameters

I have problems for insert values with a stored procedure with values as parameters and table name too. this is part of my table:
My table:
CREATE TABLE [dbo].[INGRESOLOTEMP_100]
(
[CLIENTE_CODIGO] [SMALLINT] NOT NULL,
[CAJA_CODIGO] [nvarchar](20) NULL,
[CAJA_NUMERO] [SMALLINT] NOT NULL,
)
My stored procedure:
CREATE PROCEDURE [dbo].[SP_LOT_INSERTLOTEMP]
#IDENT_TABLA NVARCHAR(10),
#CLIENTE_CODIGO SMALLINT,
#CAJA_CODIGO NVARCHAR(15),
#CAJA_NUMERO SMALLINT
AS
DECLARE #NOMBRE_TABLA NVARCHAR(40)
SELECT
#NOMBRE_TABLA = 'INGRESOLOTEMP_' + CONVERT(VARCHAR(100), #IDENT_TABLA)
SELECT
#CAJA_CODIGO = CONVERT(VARCHAR(20), #CAJA_CODIGO)
DECLARE #SQL NVARCHAR(MAX)
SET #SQL = 'INSERT into dbo.' + quotename(#NOMBRE_TABLA) +
' (CLIENTE_CODIGO, CAJA_CODIGO, CAJA_NUMERO) VALUES (' +
CONVERT(VARCHAR(20),#CLIENTE_CODIGO) + ',' + #CAJA_CODIGO + ',' +
CONVERT(VARCHAR(20),#CAJA_NUMERO) +
')'
EXEC sp_executesql #SQL
My table name is formed by a table name + an Id (every user has one)
But the problem is when I execute the stored procedure:
SP_LOT_INSERTLOTEMP 100, 123, 'uio123', 1
I have an error in SQL with value: 'uio123'
But if I execute:
SP_LOT_INSERTLOTEMP 100, 123, 80, 1
The insert is perfect, The problem is that I need insert numeric and text values, even date time values too. I realized varchar conversions in the stored procedure, but I don't get it yet.
Anyone, have an Idea?
Please I hope you can help me.
Gregg, Giorgi...
Thanks, I followed your advices, I think I get it:
ALTER PROCEDURE [dbo].[SP_LOT_INSERTLOTEMP]
#IDENT_TABLA NVARCHAR(10),
#CLIENTE_CODIGO SMALLINT,
#CAJA_CODIGO NVARCHAR(15),
#CAJA_NUMERO SMALLINT
AS
BEGIN
DECLARE #NOMBRE_TABLA NVARCHAR(40)
SELECT #NOMBRE_TABLA = 'INGRESOLOTEMP_' + CONVERT(VARCHAR(100),#IDENT_TABLA)
DECLARE #SQL NVARCHAR(MAX)
SET #SQL = 'INSERT into dbo.' + #NOMBRE_TABLA
SET #SQL += '(CLIENTE_CODIGO, CAJA_CODIGO, CAJA_NUMERO) VALUES ('
SET #SQL += CONVERT(VARCHAR(20), #CLIENTE_CODIGO) + ', '
SET #SQL += '''' + CONVERT(VARCHAR(20), #CAJA_CODIGO) + ''', '
SET #SQL += CONVERT(VARCHAR(20), #CAJA_NUMERO) + ')'
DECLARE #ParmDefinition nvarchar(500)
SET #ParmDefinition = '#IDENT_TABLA NVARCHAR(10), #CLIENTE_CODIGO SMALLINT, #CAJA_CODIGO NVARCHAR(15), #CAJA_NUMERO SMALLINT'
SELECT #sql
PRINT #sql
EXEC sp_executesql #SQL, #ParmDefinition, #IDENT_TABLA, #CLIENTE_CODIGO, #CAJA_CODIGO, #CAJA_NUMERO
END
And when I print what execution contains:
EXEC [SP_LOT_INSERTLOTEMP] 100, 123, 'UIO123', 6
I have this:
INSERT into dbo.INGRESOLOTEMP_100(CLIENTE_CODIGO, CAJA_CODIGO, CAJA_NUMERO) VALUES (123, 'UIO123', 6)
I will continue, If I have any question, I hope somebody or you, can help me.
Thanks.
The problem is in varchar column. Notice the generated statements for
EXEC SP_LOT_INSERTLOTEMP 100, 123, 'uio123', 1
EXEC SP_LOT_INSERTLOTEMP 100, 123, 80, 1
INSERT into dbo.[INGRESOLOTEMP_100] (CLIENTE_CODIGO, CAJA_CODIGO, CAJA_NUMERO) VALUES (123,uio123,1)
INSERT into dbo.[INGRESOLOTEMP_100] (CLIENTE_CODIGO, CAJA_CODIGO, CAJA_NUMERO) VALUES (123,80,1)
Try uncommenting --PRINT #SQL and see yourself the resulting statements.
You should provide additional quotes. Try this:
ALTER PROCEDURE [dbo].[SP_LOT_INSERTLOTEMP]
#IDENT_TABLA NVARCHAR(10),
#CLIENTE_CODIGO SMALLINT,
#CAJA_CODIGO NVARCHAR(15),
#CAJA_NUMERO SMALLINT
AS
DECLARE #NOMBRE_TABLA NVARCHAR(40)
SELECT #NOMBRE_TABLA = 'INGRESOLOTEMP_' + CONVERT(VARCHAR(100),#IDENT_TABLA)
SELECT #CAJA_CODIGO = CONVERT(VARCHAR(20), #CAJA_CODIGO)
DECLARE #SQL NVARCHAR(MAX)
SET #SQL = 'INSERT into dbo.' + quotename(#NOMBRE_TABLA) +
' (CLIENTE_CODIGO, CAJA_CODIGO, CAJA_NUMERO) VALUES (' +
+ CONVERT(VARCHAR(20),#CLIENTE_CODIGO) +','''/*changes here*/ + #CAJA_CODIGO + ''','/*changes here*/ +
CONVERT(VARCHAR(20),#CAJA_NUMERO) +
')'
--PRINT #SQL
EXEC sp_executesql #SQL
Several changes needed to be made to your procedure; see below:
ALTER PROCEDURE [dbo].[SP_LOT_INSERTLOTEMP]
#IDENT_TABLA NVARCHAR(10),
#CLIENTE_CODIGO SMALLINT,
#CAJA_CODIGO NVARCHAR(15),
#CAJA_NUMERO SMALLINT
AS
BEGIN
DECLARE #NOMBRE_TABLA NVARCHAR(40)
SELECT #NOMBRE_TABLA = 'INGRESOLOTEMP_' + CONVERT(VARCHAR(100),#IDENT_TABLA)
SELECT #CAJA_CODIGO = CONVERT(VARCHAR(20), #CAJA_CODIGO)
DECLARE #SQL NVARCHAR(MAX)
SET #SQL = 'INSERT into dbo.' + #NOMBRE_TABLA
SET #SQL += '(CLIENTE_CODIGO, CAJA_CODIGO, CAJA_NUMERO)
VALUES (#CLIENTE_CODIGO, #CAJA_CODIGO, #CAJA_NUMERO)'
DECLARE #ParmDefinition nvarchar(500)
SET #ParmDefinition = '#IDENT_TABLA NVARCHAR(10), #CLIENTE_CODIGO SMALLINT, #CAJA_CODIGO NVARCHAR(15), #CAJA_NUMERO SMALLINT'
SELECT #sql
EXEC sp_executesql #SQL, #ParmDefinition, #IDENT_TABLA, #CLIENTE_CODIGO, #CAJA_CODIGO, #CAJA_NUMERO
END

EXEC sp_executesql with multiple parameters

How to pass the parameters to the EXEC sp_executesql statement correctly?
This is what I have now, but i'm getting errors:
alter PROCEDURE [dbo].[usp_getReceivedCases]
-- Add the parameters for the stored procedure here
#LabID int,
#RequestTypeID varchar(max),
#BeginDate date,
#EndDate date
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
declare #statement nvarchar(4000)
set #statement = N'select SentToLab,
FROM dbo.vEmailSent
WHERE SentToLab_ID=#LabID and convert(date,DateSent) >= #BeginDate
and CONVERT(date, datesent) <= #EndDate
and RequestType_ID in ( #RequestTypeID )
EXEC sp_executesql #statement,N'#LabID int', #LabID, N'#BeginDate date', #BeginDate,N'#EndDate date', #EndDate, #RequestTypeID=#RequestTypeID
END
RequestTypeID is a comma delimited list of integers, like so: "1,2,3,4,5"
here is my try #2, also unsuccessful
declare #statement nvarchar(4000)
SET #statement =' select SentToLab_ID
FROM dbo.vEmailSent
WHERE
SentToLab_ID='+#LabID+' and convert(date,DateSent) >= '+#BeginDate +'
and CONVERT(date, datesent) <= '+#EndDate+'
and RequestType_ID in ('+ #RequestTypeID+' )
group by FileStream_ID, SentToLab_ID'
EXEC(#statement)
Operand type clash: date is incompatible with int
Here is a simple example:
EXEC sp_executesql #sql, N'#p1 INT, #p2 INT, #p3 INT', #p1, #p2, #p3;
Your call will be something like this
EXEC sp_executesql #statement, N'#LabID int, #BeginDate date, #EndDate date, #RequestTypeID varchar', #LabID, #BeginDate, #EndDate, #RequestTypeID
This also works....sometimes you may want to construct the definition of the parameters outside of the actual EXEC call.
DECLARE #Parmdef nvarchar (500)
DECLARE #SQL nvarchar (max)
DECLARE #xTxt1 nvarchar (100) = 'test1'
DECLARE #xTxt2 nvarchar (500) = 'test2'
SET #parmdef = '#text1 nvarchar (100), #text2 nvarchar (500)'
SET #SQL = 'PRINT #text1 + '' '' + #text2'
EXEC sp_executeSQL #SQL, #Parmdef, #xTxt1, #xTxt2
If one need to use the sp_executesql with OUTPUT variables:
EXEC sp_executesql #sql
,N'#p0 INT'
,N'#p1 INT OUTPUT'
,N'#p2 VARCHAR(12) OUTPUT'
,#p0
,#p1 OUTPUT
,#p2 OUTPUT;
maybe this help :
declare
#statement AS NVARCHAR(MAX)
,#text1 varchar(50)='hello'
,#text2 varchar(50)='world'
set #statement = '
select '''+#text1+''' + '' beautifull '' + ''' + #text2 + '''
'
exec sp_executesql #statement;
this is same as below :
select #text1 + ' beautifull ' + #text2

Passing negative values into stored procedure

I am trying to insert ID values in stored procedure from .net and the int value for ID is inserting negative value in the stored procedure.
But when a negative value is passed its giving me an error incorrect syntax near '*'.
Please help me.
Here is my stored procedure
ALTER PROCEDURE [dbo].[HotlinePlusAdministration_ArticleMigrator]
#Id AS INT,
--#CategoryID AS INT,
--#Title AS Varchar(200),
--#ArticleDate AS datetime,
#DestLinkServer AS VARCHAR(50),
#UserID AS VARCHAR(8),
#ReturnMsg AS VARCHAR(1000) OUTPUT
AS
BEGIN
DECLARE #Query AS NVARCHAR(4000)
DECLARE #Log AS VARCHAR(8000)
DECLARE #ArticleID as int
DECLARE #NewArticleID as int
DECLARE #ArticleKeyExists as int
DECLARE #Title as varchar(200)
DECLARE #CategoryID as INT
DECLARE #ArticleDate as varchar(30)
DECLARE #ParmDefinition nvarchar(500);
SET XACT_ABORT ON -- Required for nested transaction
BEGIN TRAN
-- Check if ArticleID exists in Destination Server
SET #Query = N' SELECT #ArticleKeyExists = COUNT(*)
FROM ' + #DestLinkServer + '.HL2_61.dbo.Article' + ' where ArticleKey = ' + str(#Id)
SET #ParmDefinition = N' #ID int, #ArticleKeyExists int OUTPUT';
EXECUTE sp_executesql #Query , #ParmDefinition, #ID, #ArticleKeyExists OUTPUT;
--EXECUTE sp_executesql 1234,'BRHLSQL8','BRWSQLDC',#return = retnmsg
IF ##ERROR <> 0
BEGIN
ROLLBACK TRANSACTION
SET #ReturnMsg = #Log + '<span style="color:red;">ERROR: <br></span>'
RETURN -1
END
--Delete existing Articles for select page
set #Query = 'DELETE FROM ' + #DestLinkServer +
'.HL2_61.dbo.Article ' +
'WHERE ArticleKey = ' + CONVERT(VARCHAR, #Id)
--'WHERE CategoryID = ' + CONVERT(VARCHAR, #CategoryID) + ' and Title = ''' + #Title + ''' and ArticleDate = ''' + #ArticleDate + ''''
Print #Query
EXEC(#Query)
When I am executing the code as below I am getting the error.
DECLARE #return_value int,
#ReturnMsg varchar(1000)
EXEC #return_value = [dbo].[Migrator]
#Id = -1591276581,
#DestLinkServer = N'SQLDC',
#UserID = N'10c1',
#ReturnMsg = #ReturnMsg OUTPUT
SELECT #ReturnMsg as N'#ReturnMsg'
SELECT 'Return Value' = #return_value
GO
Please someone help me..
Thanks
When you convert an int to a varchar, you have to specify the size:
Try this:
CONVERT(VARCHAR(50), #Id)
and avoid using str(#Id)

Resources