使用带有链接服务器的like子句在日期时间中使用变量的Openquery

2021-09-10 00:00:00 tsql sql-server openquery

每次执行此查询时,都会收到此错误:数据类型 varchar 和 varchar 在模运算符中不兼容.寻求你的帮助.谢谢!

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;

推荐答案

你可以是 varchar(4) 因为你将它设置为字符串.然后使用 datepart()

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;

相关文章