简体   繁体   English

动态 SQL 使用同一表中的随机值更新表

[英]Dynamic SQL to update table with random values from the same table

I want to create a dynamic SQL in a stored procedure that takes a table name as a parameter and for each column in that table the values will be updated with a random value from the same column.我想在将表名作为参数的存储过程中创建一个动态 SQL,并且对于该表中的每一列,值将使用来自同一列的随机值进行更新。
( I need this to create tables for testing purposes so that I don't use real data ). 我需要它来创建用于测试目的的表,以便我不使用真实数据)。
For example let's say I have the table 'students' below:例如,假设我有下面的表格“学生”:

|ID| FName|  BirthDay |
-----------------------
|1 | Mike | 1993-07-24|
-----------------------
|2 | John | 1995-10-11|
-----------------------
|3 | Bob  | 1992-04-13|
-----------------------

After the update the values will be updated randomly using the same values from the table:更新后,这些值将使用表中的相同值随机更新:

|ID| FName|  BirthDay |
-----------------------
|2 | Bob  | 1995-10-11|
-----------------------
|3 | John | 1995-10-11|
-----------------------
|3 | Mike | 1992-04-13|
-----------------------

For the random value I tried something like this:对于随机值,我尝试了这样的事情:

 UPDATE students
   SET ID = SELECT TOP 1 ID FROM students ORDER BY NEWID()
   SET FName = SELECT TOP 1 FName FROM students ORDER BY NEWID()
   SET Birthday = SELECT TOP 1 Birthday FROM students ORDER BY NEWID()

Do you have any idea how to implement this as a stored procedure(SQL Server) so i can use it with any table given as a parameter?您知道如何将其实现为存储过程(SQL Server),以便我可以将它与作为参数给出的任何表一起使用?

Later edit : I have done this so far (it takes the table name as parameter and updates every column it finds in that table but the problem is that after update all the values in a column are the same).稍后编辑:到目前为止我已经这样做了(它以表名作为参数并更新它在该表中找到的每一列,但问题是更新后一列中的所有值都相同)。
Here is the code:这是代码:

CREATE PROCEDURE [dbo].[RandomUpdate]
   @TableName NVARCHAR(100)
    AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    DECLARE @sql NVARCHAR(MAX) = (
    SELECT ' UPDATE ' + @TableName--note the extra space at the beginning
        + ' SET ' + QUOTENAME(c.name) + ' = ' + '(SELECT TOP 1 ' + QUOTENAME(c.name) + ' FROM ' + @TableName + ' ORDER BY NEWID());' 
    FROM sys.columns c
    WHERE c.object_id = OBJECT_ID(@TableName)
    FOR XML PATH('')
)
    PRINT @sql;
    EXEC sp_executesql @sql


END

and the output is like this:输出是这样的:

|ID| FName|  BirthDay |
-----------------------
|3 | Bob  | 1995-10-11|
-----------------------
|3 | Bob  | 1995-10-11|
-----------------------
|3 | Bob  | 1995-10-11|
-----------------------

Any ideas how to set different values?任何想法如何设置不同的值?

只需将以下内容添加到 SQL 语句的顶部 CREATE PROCEDURE [nameofprocedure] AS

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM