저장 프로 시저에서 입력 변수로 테이블 이름을 전달합니다.테이블의 행 수를 찾는 저장 프로 시저
이 저장 프로 시저로이 테이블의 행 수를 반환하고자합니다.
나는 이런 식으로 뭔가를 시도했지만 작동하지 않았다 :declare @maxRowCount bigint
exec('set '+ @maxRowCount + ' =(select COUNT(1) from ' + @tableName + ')')
이 SQL 서버 2008
저장 프로 시저에서 입력 변수로 테이블 이름을 전달합니다.테이블의 행 수를 찾는 저장 프로 시저
이 저장 프로 시저로이 테이블의 행 수를 반환하고자합니다.
나는 이런 식으로 뭔가를 시도했지만 작동하지 않았다 :declare @maxRowCount bigint
exec('set '+ @maxRowCount + ' =(select COUNT(1) from ' + @tableName + ')')
이 SQL 서버 2008
당신은 @maxRowCount
주위에 따옴표를 제거해야합니다.
이 시도 :
declare @maxRowCount bigint
exec('set @maxRowCount =(select COUNT(*) from ' + @tableName + ')')
또는
exec('SELECT @maxRowCount = COUNT(*) from ' + @tableName)
분석 : 당신이 시도 쿼리와
를, 그것은 실행됩니다
set blablabla = (select count(1) from MyTable)
따옴표를 제거함으로써
:
set @maxRowCount = (select count(*) from MyTable)
대신이 시도 할 수 있습니다.
declare @maxRowCount bigint(5)
exec('SELECT COUNT(*) INTO @maxRowCount FROM ' + @tableName)
'@maxRowCount'근처의 구문이 잘못되었습니다. 이것이 내가 얻는 것입니다. –
다음 예제는 사용할 항목을 제공해야합니다.
-- fully qualify your table name (this is probably an input value in your sproc?)
-- please note that I use system view master.sys.tables as an example table here
DECLARE @tablename NVARCHAR(MAX) = N'[master].[sys].[tables]';
-- build the sql statement that you will execute
DECLARE @sql NVARCHAR(MAX) = N'SELECT COUNT(*) FROM ' + @tablename;
-- create a variable to hold the number of rows later on
DECLARE @nrofrows BIGINT;
-- create a temp table to store the result of executing the sql statement
CREATE TABLE #temp (NrOfRows BIGINT);
-- insert the result of the execution of the sql statement into the temp table
INSERT INTO #temp
EXECUTE(@sql);
-- extract the number of rows from the temp table
SET @nrofrows = (SELECT NrOfRows FROM #temp);
-- check the result so you can test!
PRINT @nrofrows;
당신은 Erland Sommarskog의 기사 The Curse and Blessings of Dynamic SQL을 확인, 동적 SQL에 대한 좋은 배경 정보를합니다.
이
CREATE PROCEDURE dbo.sp_selectcount
@tablename NVARCHAR(200)
AS
DECLARE @cmd NVARCHAR (255)
SET @cmd = 'SELECT count(*) from ' + @tablename
EXEC sp_executesql @cmd
은 스칼라 변수 "@maxRowCount"를 선언해야 시도 할 수 있습니다. 이 오류가 발생합니다 –
내 저장 프로 시저에서 최대 개수를 원한다는 것이 제 목적에 부합하지 않습니다. –