传递多个参数

https://stackoverflow.com/questions/28481189/exec-sp-executesql-with-multiple-parameters

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

https://docs.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-executesql-transact-sql?view=sql-server-2017

DECLARE @IntVariable int;
DECLARE @SQLString nvarchar(500);
DECLARE @ParmDefinition nvarchar(500); /* Build the SQL string one time.*/
SET @SQLString =
N'SELECT BusinessEntityID, NationalIDNumber, JobTitle, LoginID
FROM AdventureWorks2012.HumanResources.Employee
WHERE BusinessEntityID = @BusinessEntityID';
SET @ParmDefinition = N'@BusinessEntityID tinyint';
/* Execute the string with the first parameter value. */
SET @IntVariable = 197;
EXECUTE sp_executesql @SQLString, @ParmDefinition,
@BusinessEntityID = @IntVariable;
/* Execute the same string with the second parameter value. */
SET @IntVariable = 109;
EXECUTE sp_executesql @SQLString, @ParmDefinition,
@BusinessEntityID = @IntVariable;

传递表变量作为参数(比较麻烦,需要自定义表类型)

错误提示为

Must declare the table variable "@TempTable".

因为需要自定义表类型,显得比较麻烦。所以,如果只是单纯的需要表操作,可以考虑dynamic sql拼接临时表。参考下一个标题1

https://stackoverflow.com/questions/7329996/using-table-variable-with-sp-executesql

Here's an example of how to pass a table-valued parameter to sp_executesql. The variable has to be passed readonly:

if exists (select * from sys.types where name = 'TestTableType')
drop type TestTableType create type TestTableType as table (id int)
go
declare @t TestTableType
insert @t select 6*7 exec sp_executesql N'select * from @var', N'@var TestTableType readonly', @t

This prints the Answer to the Ultimate Question of Life, the Universe, and Everything.

传递临时表作为参数(无法实现,只能通过dynamic sql进行拼接)

https://stackoverflow.com/questions/4258798/pass-a-table-variable-to-sp-executesql

While this may not directly answer your question, it should solve your issue overall.

You can indeed capture the results of a Stored Procedure execution into a temporary table:

INSERT INTO #workingData
EXEC myProc

So change your code to look like the following:

CREATE TABLE #workingData ( col1 VARCHAR(20),
col2 VARCHAR(20) ) INSERT INTO #workingData
EXEC myProc DECLARE @sql NVARCHAR(MAX)
SET @sql = 'SELECT * FROM #workingData' EXEC sp_executesql @sql

Regards, Tim

将表名作为参数进行传递

https://stackoverflow.com/questions/20156157/how-to-pass-a-table-variable-using-sp-executesql

这个很可能会导致sql 注入。
如果可以确保不是用户输入的话,就可以避免sql注入

Figured out the problem.

Apparently sp_executesql expects the parameter definition for a table to be of a table type (see this answer for an example: https://stackoverflow.com/a/4264553/21539).

An easier way to solve this problem was to insert the variables names directly into the SQLStatement string as follows:

DECLARE @SQLString NVARCHAR(MAX),
@TableName NVARCHAR(MAX); SET @TableName = N'[dbo].[MyTable]'; SET @SQLString = N'SELECT * FROM ' + @TableName + ';'; SET @ParamDefinition = N'@_TableName NVARCHAR(max); EXEC sp_executesql @SQLString;

https://stackoverflow.com/questions/1246760/how-should-i-pass-a-table-name-into-a-stored-proc/1246848#1246848

First of all, you should NEVER do SQL command compositions on a client app like this, that's what SQL Injection is. (Its OK for an admin tool that has no privs of its own, but not for a shared use application).

Secondly, yes, a parametrized call to a Stored procedure is both cleaner and safer.

However, as you will need to use Dynamic SQL to do this, you still do not want to include the passed string in the text of the executed query. Instead, you want to used the passed string to look up the names of the actual tables that the user should be allowed to query in the way.

Here's a simple naive example:

CREATE PROC spCountAnyTableRows( @PassedTableName as NVarchar(255) ) AS
-- Counts the number of rows from any non-system Table, *SAFELY*
BEGIN
DECLARE @ActualTableName AS NVarchar(255) SELECT @ActualTableName = QUOTENAME( TABLE_NAME )
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = @PassedTableName DECLARE @sql AS NVARCHAR(MAX)
SELECT @sql = 'SELECT COUNT(*) FROM ' + @ActualTableName + ';' EXEC(@SQL)
END

Some have fairly asked why this is safer. Hopefully, little Bobby Tables can make this clearer:


Answers to more questions:

  1. QUOTENAME alone is not guaranteed to be safe. MS encourages us to use it, but they have not given a guarantee that it cannot be out-foxed by hackers. FYI, real Security is all about the guarantees. The table lookup with QUOTENAME, is another story, it's unbreakable.

  2. QUOTENAME is not strictly necessary for this example, the Lookup translation on INFORMATION_SCHEMA alone is normally sufficient. QUOTENAME is in here because it is good form in security to include a complete and correct solution. QUOTENAME in here is actually protecting against a distinct, but similar potential problem know as latent injection.

sp_executesql 无法识别临时表或者表变量

https://stackoverflow.com/questions/8040105/execute-sp-executesql-for-select-into-table-but-cant-select-out-temp-table-d

问题:

Was trying to select...into a temp Table #TempTable in sp_Executedsql. Not its successfully inserted or not but there Messages there written (359 row(s) affected) that mean successful inserted? Script below

DECLARE @Sql NVARCHAR(MAX);
SET @Sql = 'select distinct Coloum1,Coloum2 into #TempTable
from SPCTable with(nolock)
where Convert(varchar(10), Date_Tm, 120) Between @Date_From And @Date_To'; SET @Sql = 'DECLARE @Date_From VARCHAR(10);
DECLARE @Date_To VARCHAR(10);
SET @Date_From = '''+CONVERT(VARCHAR(10),DATEADD(d,DATEDIFF(d,0,GETDATE()),0)-1,120)+''';
SET @Date_To = '''+CONVERT(VARCHAR(10),DATEADD(d,DATEDIFF(d,0,GETDATE()),0)-1,120)+''';
'+ @Sql; EXECUTE sp_executesql @Sql;

After executed,its return me on messages (359 row(s) affected). Next when trying to select out the data from #TempTable.

Select * From #TempTable;

Its return me:

Msg 208, Level 16, State 0, Line 2
Invalid object name '#TempTable'.

Suspected its working only the 'select' section only. The insert is not working. how fix it?

解答:

Local temporary table #table_name is visible in current session only, global temporary ##table_name tables are visible in all sessions.

Both lives until their session is closed.

sp_executesql - creates its own session (maybe word "scope" would be better) so that's why it happens.

可以识别的临时表

如果是在存储过程内部

select

into #TempTable

那么这个是可以在拼接的sql中识别的。

上面的例子无法识别,是因为那里的#TempTable是单独执行的,并不属于存储过程

EXEC sp_executesql with multiple parameters的更多相关文章

  1. EXEC sp_executesql

    declare @sql nvarchar(max)declare @nu int set @sql='SELECT * FROM [FMTest].[dbo].[FM_Radio_Station]' ...

  2. 动态sql语句基本语法--Exec与Exec sp_executesql 的区别

    http://www.cnblogs.com/goody9807/archive/2010/10/19/1855697.html 动态sql语句基本语法 1   :普通SQL语句可以用Exec执行   ...

  3. 动态SQL的执行,注:exec sp_executesql 其实可以实现参数查询和输出参数的

    本文转自:http://www.cnblogs.com/hnsdwhl/archive/2011/07/23/2114730.html 当需要根据外部输入的参数来决定要执行的SQL语句时,常常需要动态 ...

  4. Can't bind multiple parameters ('header' and 'parameters') to the request's content.

    2019-01-23 15:46:29.012+08:00 ERROR [6]: System.InvalidOperationException: Can't bind multiple param ...

  5. SQL:exec sp_executesql 用法

    --這種是無效的過程 declare @sql nvarchar(500), @where nvarchar(500),@i nvarchar(64),@p nvarchar(50),@id int ...

  6. MS SqlServer之Exec和EXEC SP_EXECUTESQL

    exec执行sql时字符串时,不能给变量赋值,如果要在sql里给变量赋值,请用EXEC SP_EXECUTESQL 示例: 通过 SP_EXECUTESQL 的第2个参数来定义有哪些参数 输出的加OU ...

  7. exec sp_executesql 比直接执行SQL慢,而且消耗大量资源问题

    今天SqlServer数据库出现了访问不通的情况,抓紧重启了下服务,让大家先恢复使用,然后我开了 SQL Server Profiler 看看是不是存在性能问题SQL,然后就发现一批这样的SQL,看r ...

  8. JNI: Passing multiple parameters in the function signature for GetMethodID

    http://stackoverflow.com/questions/7940484/jni-passing-multiple-parameters-in-the-function-signature ...

  9. [Angular 2] Pipes with Multiple Parameters

    Showing how to set up a Pipe that takes multiple updating inputs for multiple Component sources. imp ...

随机推荐

  1. 【Swing/文本组件】定义自动换行的文本域

    文本域组件:Swing中任何一个文本域(JTextArea)都是JTestArea类型的对象.常用的构造方法如下 public JTextArea() public JTextArea(String ...

  2. mysql中主外键关系

    一.外键: 1.什么是外键 2.外键语法 3.外键的条件 4.添加外键 5.删除外键 1.什么是外键: 主键:是唯一标识一条记录,不能有重复的,不允许为空,用来保证数据完整性 外键:是另一表的主键, ...

  3. Excel GET.CELL说明

    GET是得到的意思CELL是单元格的意思  --->那么它的意思就是你想得到单元格的什么东西(信息)  函数定义:  GET.CELL(类型号,单元格(或范围))  其中类型号,即你想要得到的信 ...

  4. 电子产品使用感受之———我用过的最昂贵的手机壳:otter box 和 Apple 原装清水壳的对比

    2014年9月27日,我买到了我所使用的第一部 iPhone — iPhone 5C 蓝色.今天,2019年3月2日,我手里拿的是iPhoneXR 蓝色,两款手机如出一辙的设计和手感,让我充满了无限的 ...

  5. 程序中打印当前进程的调用堆栈(backtrace)

    为了方便调式程序,产品中需要在程序崩溃或遇到问题时打印出当前的调用堆栈.由于是基于Linux的ARM嵌入式系统,没有足够的空间来存放coredump文件. 实现方法,首先用__builtin_fram ...

  6. Xmodem协议简介

    1.      Xmodem协议 1.1.    简介 在上一章中,BootLoader和APP在串口下的升级其实都用到了一种文件传输协议,即Xmodem协议,该协议因其简单,易实现和使用的特点在很多 ...

  7. RoR - Expressing Database Relationships

    One-to-One Association: *一个person只对应一个personal_info *一个personal_info只属于一个person *belongs to用foreign ...

  8. Mac系统显示隐藏文件及文件夹

    显示隐藏文件 终端 输入如下命令,回车即可: defaults write com.apple.finder AppleShowAllFiles -boolean true ; killall Fin ...

  9. container_of 例子说明

    很早前之前看的linux内核,一直想把container_of记录一下,趁今天想起就记录一下: 内核中的描述 /** * container_of - cast a member of a struc ...

  10. CS1704问题汇总

    “/”应用程序中的服务器错误. 编译错误 说明: 在编译向该请求提供服务所需资源的过程中出现错误.请检查下列特定错误详细信息并适当地修改源代码. 编译器错误消息: CS1704: 已经导入了具有相同的 ...