--- Dynamic script workout
DECLARE
@SQL NVARCHAR(500),
@SQLOut NVARCHAR(500),
@UserName NVARCHAR(50),
@Columns NVARCHAR(100),
@ParmDefinition NVARCHAR(100),
@ParmDefinitionOut NVARCHAR(100),
@Table NVARCHAR(128),
@PersonID INT;
CREATE TABLE #Person
(
[PersonId] INT,
[FirstName] NVARCHAR(25),
[LastName] NVARCHAR(25),
[UserName] NVARCHAR(50)
);
INSERT INTO #Person
VALUES
( 1, N'Default', N'Default', N'Default.com.np' ),
( 2, N'Mik', N'User', N'admin@ad.com' ),
( 3, N'Kaww', N'Poudel', N'jhjv@gg.com.np' );
SET @Columns = 'FirstName, LastName,UserName';
SET @Table = '#Person';
SET @PersonID = 2;
-- adhoc - script
SET @SQL = 'SELECT ' + @Columns + ' FROM ' + @Table + ' WHERE PersonId = ' + CAST(@PersonID AS VARCHAR(10));
EXEC ( @SQL );
-- dynamic script
SET @SQL = 'SELECT ' + @Columns + ' FROM ' + @Table + ' WHERE PersonId = @PersonIDNew';
SET @ParmDefinition = N'@PersonIDNew INT';
EXEC sys.sp_executesql
@SQL,
@ParmDefinition,
@PersonIDNew = @PersonID;
-- dynamic script with Output
SET @SQLOut = 'SELECT @UserNameOut = UserName FROM ' + @Table + ' WHERE PersonId = @PersonIdIn';
SET @ParmDefinitionOut = N'@PersonIdIn INT, @UserNameOut NVARCHAR(50) OUTPUT';
EXEC sys.sp_executesql
@SQLOut,
@ParmDefinitionOut,
@PersonIdIn = @PersonID,
@UserNameOut = @UserName OUTPUT
SELECT @UserName
DROP TABLE #Person;
Comments
Post a Comment