Openquery with variables in datetime using like clause with linked server - sql-server

Everytime I execute this query I get this error:
The data types varchar and varchar are incompatible in the modulo operator. Asking for your help. Thanks!
DECLARE #date datetime, #SQL NVARCHAR(MAX);
SET #date = '2019';
SET #SQL = 'SELECT * FROM OPENQUERY(LINK2, ''SELECT * FROM wordpress.wp_users WHERE user_registered LIKE '''%' +#date+ '%''''')';
EXEC sp_executesql #SQL;

you can be varchar(4) because you are setting it as string. then use datepart()
DECLARE #date varchar(4), #SQL NVARCHAR(MAX);
SET #date = '2019';
SET #SQL = 'SELECT * FROM OPENQUERY(LINK2, ''SELECT * FROM wordpress.wp_users WHERE DATEPART(yy, user_registered) LIKE ''''%' +#date+ '%'''''')';
EXEC sp_executesql #SQL;

Related

Parameterized dynamic query within cursor causes ERROR "Procedure expects parameter '#params' of type 'ntext/nchar/nvarchar'"

I need to get the max edit date for each table in our database and store in a temp table. The cursor works fine but when I run exec sp_executesql #sql I get a parameter expectation error:
Parameterized dynamic query within Cursor gives ERROR Procedure expects parameter '#params' of type 'ntext/nchar/nvarchar'
What am I doing wrong?
SET NOCOUNT ON
IF OBJECT_ID('tempdb..##GetMaxVistaEditDate') IS NOT NULL
DROP TABLE ##GetMaxVistaEditDate
CREATE TABLE ##GetMaxVistaEditDate
(
MySchema nvarchar(max),
MyTable nvarchar(max),
MaxVistaEditDate DateTime
)
-- SELECT * FROM ##GetMaxVistaEditDate
DECLARE MyCursor CURSOR FOR
SELECT
SCHEMA_NAME(t.schema_id) Schemaname,
t.name AS TableName
FROM
sys.tables t
WHERE
Schema_Name(t.Schema_id) like 'R_PERS%'
OPEN MyCursor
DECLARE #Schema VARCHAR(100), #Table VARCHAR(100), #MaxVistaEditDate DATETIME
DECLARE #sql NVARCHAR(MAX) = '', #params NVARCHAR(MAX);
SET #params = N'#MaxVistaEditDate DateTime OUTPUT';
FETCH FROM MyCursor INTO #Schema, #Table
WHILE ##FETCH_STATUS = 0
BEGIN
SET #SQL = 'DECLARE #MaxVistaEditDate DATETIME SELECT #MaxVistaEditDate = (SELECT MAX(VistaEditDate) FROM ' + #SCHEMA + '.' + #TABLE + ')'
EXEC sp_executesql #sql, #MaxVistaEditDate OUTPUT
-- PRINT #SQL
-- PRINT #MaxVistaEditDate
INSERT INTO ##GetMaxVistaEditDate
SELECT #Schema, #Table, #MaxVistaEditDate
FETCH FROM MyCursor INTO #Schema, #Table
END
CLOSE MyCursor
DEALLOCATE MyCursor
You don't have to declare the variables on the sql string, you have to do it on a different variable, and you already have one for that (you name it #params).
Change your #sql definition for the following
SET #SQL = 'Select #MaxVistaEditDate = (SELECT MAX(VistaEditDate) From ' + #SCHEMA + '.' + #TABLE + ')'
And change your call for this:
exec sp_executesql #sql ,#params, #MaxVistaEditDate = #MaxVistaEditDate OUTPUT
and it should work.
Note: Don't forget to close and deallocate the cursor.
you can find an answer in this post
SP_EXECUTESQL and Output Parameter
and your sp_executesql statement don't have parameter definition and you don't have to declare a variable inside the dynamic query
declare #MaxVistaEditDate datetime
exec sp_executesql #sql ,N'#MaxVistaEditDateOut datetime OutPut, #MaxVistaEditDateOut=#MaxVistaEditDate OUTPUT

Concatenate DateTime (yyyy-MM-dd HH:mm:ss.fff) to a string in a dynamic sql query

I have below DateTime value obtained using T-SQL GetDate() function and I am trying to concatenate it to a dynamic SQL query.
2020-02-25 11:35:29.240
and I am trying to concatenate to a WHERE clause like this:
CREATE PROCEDURE dbo.MyProc
#paramList varchar(200)
AS
BEGIN
DECLARE #sqlCommand nvarchar(max)
DECLARE #Now DATETIME = Getdate()
-- Do some stuff
SET #sqlCommand ='SELECT * FROM MyTable WHERE DeptId IN (' + #paramList + ') AND ''' + #Now + ''' <= datetimeField'
EXECUTE sp_executesql #sqlCommand
END
but it does not work.
Note: #paramList is a sp parameter that comes from C# .NET.
You can use use sp_executesql with parameter:
SET #sqlCommand ='SELECT * FROM MyTable WHERE #now <= datetimeField'
EXECUTE sp_executesql #sqlCommand, N'#now datetime', #Now = #Now
However, simple query will do what you want :
DECLARE #Now DATETIME = GETDATE()
SELECT *
FROM MyTable
WHERE datetimeField <= #Now;

SQL Conversion failed when converting date and/or time

DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX),
#startdate datetime = '2017-04-01',
#enddate datetime = '2017-04-30'
SET #query = '
select * from Tb_T_Article where Created_Date < convert(date,' +#enddate+ ',105)
'
print #query
EXEC SP_EXECUTESQL #query
Hey please try the below code, and see if that works
DECLARE #enddate datetime
DECLARE #query NVARCHAR(MAX)
SET #enddate = '02-02-2012 6:10:00:000'
SET #query = 'SELECT CONVERT(DATE,#enddate,105)'
EXEC SP_EXECUTESQL #query,N'#enddate date',#enddate

How can I use a local variable in SELECT FROM?

I declared a variable #Obj and assign a complete table name 'ODS..Account' to it.
DECLARE #Obj VARCHAR(255)
Then I used it in a query immediately after FROM Clause. I perceive it is just a string, unable to act as a table object. So how can I fix the code to get it works? Cheers
INSERT Control.dbo.Consistency_Check
(Table_Name
,Schema_Name
,Id
,Incremental_DateTime_Column
)
SELECT
#Tab
,'ODS'
,Id
,SystemModstamp
FROM
#Obj )
You can use a local variable as a scalar value, not as a function. To do this, you need dynamic SQL:
declare #sql varchar(max);
select #sql = '
INSERT Control.dbo.Consistency_Check(Table_Name, Schema_Name, Id, Incremental_DateTime_Column)
SELECT ''#Tab'', 'ODS', Id, SystemModstamp
FROM #Tab
';
select #sql = replace(#sql, '#tab', #tab);
exec sp_executesql #sql;
Slightly different way of doing it with dynamic SQL:
DECLARE #Obj VARCHAR(255) = 'dbo.table'
DECLARE #SQL NVARCHAR(MAX) = ''
SET #SQL = #SQL +
'INSERT Control.dbo.Consistency_Check
(Table_Name
,Schema_Name
,Id
,Incremental_DateTime_Column
)
SELECT
#Tab
,''ODS''
,Id
,SystemModstamp
FROM
' + #Obj + ''
EXEC (#SQL)
You cannot. You probably want to use dynamic query. i.e. workout the SQL query string into a variable and exec using sp_executesql.
You may use the same variable name in the dynamic SQL but I changed it to #p_Tab for the example.
DECLARE #Tab int = 3
DECLARE #SQLString nvarchar(500)
DECLARE #ParmDefinition nvarchar(500) = N'#p_Tab int';
Declare #TableName nvarchar(100) = 'ODS..Account'
/* Build the SQL string dynamicly.*/
SET #SQLString = N'INSERT Control.dbo.Consistency_Check
(Table_Name
,Schema_Name
,Id
,Incremental_DateTime_Column
)
SELECT
#p_Tab
,''ODS''
,Id
,SystemModstamp
FROM
'+ #TableName
EXECUTE sp_executesql #SQLString, #ParmDefinition,
#p_Tab = #Tab
Further reference: https://msdn.microsoft.com/en-us/library/ms188001.aspx

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

Resources